I have an AsyntTask which starts in onCreate and loops infinitely, updating an UI element.
The update is done in this manner (simplified representation of the Async extending class, let’s call it asyncExtender().execute()):
doInBackground(){
while (!isCancelled()) {
Thread.sleep(2000);
publishProgress(someValue);
}
}
protected void onProgressUpdate() {
super.onProgressUpdate(values);
// UI update here, e.g. TextView.setText
}
Another activity is started, let’s call it SecondActivity. SecondActivity takes advantage of the hierarchical back button in the action bar to return to the previous activity (NavUtils.navigateUpFromSameTask(this) in onOptionsItemSelected).
The issues is that when I tap on the back button in the action bar in SecondActivity, the AsyncTask seems to not run anymore in the first activity (the UI doesn’t get updated every 2 seconds). On the other hand, if I use the hardware “back” button it works fine – the AsyncTask keeps running.
Why the difference in behaviour and how to fix it?
AsyncTasks should not be started simultanously and they also are not designed to be run for too long, at most few seconds. Depending which API you target, AsyncTasks might be run synchronously, so your new AsyncTask will be run only when all previous ones finished, excerpt for docs:
http://developer.android.com/reference/android/os/AsyncTask.html