Skip to content Skip to sidebar Skip to footer

Terminating An Async Task After Activity Is Lost

Here is my process and problem: In this application you click a Menu button From this Menu you press a toggle button, which starts an Async-Task (makes a tone sound every 30 secon

Solution 1:

You should stop the a sync task as soon as the activity destroyed/stoped if there is no need in it,

@OverridepublicvoidonStop(){
    mTask.cancel();
}

see this for more info about canceling a sync task Android - Cancel AsyncTask Forcefully

Solution 2:

I think you should not use the AsyncTask API, which is intended for running a time consuming task in a background thread and provides hooks to update the UI when it finishes or has intermediate results.

You can simply use a Runnable and the singleton pattern to locate the instance across activities constructions and destructions. Something like (singleton boilerplate omitted for brevity)

publicclassPlayerimplementsRunnable {

  publicstaticvoidstart() {}

  @Overridepublicvoidrun() {
    while (alive) {
      playSound();
      sleep();
    }
  }

  publicstaticvoidstop() {}

  publicstaticbooleanisAlive() {}

}

Then, when you initialize your widgets:

checkbox.setChecked(Player.isAlive());
checkbox.setOnCheckedStateChangeListener(newOnCheckedChangeListener(){
  @OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked)
      Player.start();
    elsePlayer.stop();
  }
});

This way your background thread is completely independent from any Activity which started it.

Post a Comment for "Terminating An Async Task After Activity Is Lost"