The service can’t call progressBar.setProgress()
directly. He needs to find a way to ask Activity
visible at that time when this method is called.
I see two possibilities: the first, which is not my favorite because it is a little more complicated, is to engage (bind) to the service and thus allow the service to communicate with the Activity
in question. In order to do this, reference should be made to a listener
that the service goes calling every time progress
should be increased. In Activity
, the listener
executes progressBar.setProgress()
. The documentation explains how to do connect to a service.
The second, which I prefer, is to transmit updates from progress
via broadcast. You record a BroadcastReceiver
associated with the life cycle of its Activity
(for example, is made the registerReceiver()
in onResume()
and the unregisterReceiver()
in onPause()
- a question of mine here, I’m not sure if the best methods for this are the pair onResume()/onPause()
or onStart()/onStop()
). And when the Activity
gets a broadcast intent
containing the new value of progress
, flame progressBar.setProgress()
.
Code you can rely on:
Minhaactivity.java:
public class MinhaActivity extends Activity {
private BroadcastReceiver mReceiver;
private IntentFilter mFilter;
protected void onCreate(Bundle savedInstanceState) {
mFilter = new IntentFilter();
mFilter.addAction("ATUALIZA_PROGRESSO");
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if ("ATUALIZA_PROGRESSO".equals(intent.getAction())) {
mProgressBar.setProgress(intent.getIntExtra("progress"));
if (intent.getIntExtra("progress") >= 100) {
mProgressBar.dismiss();
}
}
}
}
mProgressBar = new ProgressDialog(v.getContext());
mProgressBar.setCancelable(true);
mProgressBar.setMessage("Exportando os dados...");
mProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressBar.setProgress(0);
mProgressBar.setMax(100);
}
public void onClick(View v) {
// inicia o progressbar
mProgressBar.show();
// Inicia o serviço
startService(new Intent(this, MeuServico.class));
}
protected void onResume() {
registerReceiver(mReceiver, mFilter);
}
protected void onPause() {
unregisterReceiver(mReceiver);
}
Meuservice.java
public class MeuService extends IntentService {
protected void onHandleIntent(Intent intent) {
while (tarefaNaoTerminada) {
(...)
Intent intentAEnviar = new Intent("ATUALIZA_PROGRESSO");
intentAEnviar.putExtra("progress", progresso);
sendBroadcast(intentAEnviar);
}
}
}
Great! That’s what I need Piovezan, thank you so much.
– Emerson Barcellos
@Emersonbarcellos Glad you helped. If the answer is what you needed, you can accept it.
– Piovezan