I have the following situation
- I spawn a long running user thread (
Thread) from anActivity. - I press soft back button. So, the
Activitywas destroyed. - I launch the same
Activityagain. Note, the previous launchedThreadis still running.
In order for me to prevent the Activity from launching another same Thread while the previous Thread is still running, here is what I am doing
- After I launch the
Thread, I will store it into a static variable. So, next time when I try to launch a same thread, I will check against the liveness of previous thread through the static variable. Is this a good practice? What is the best practice to overcome this?
Note, the user thread is holding reference to the Activity which launched it. However, the Activity might destroyed when user press on soft back button. So, when I launch the new Activity again, the thread is not aware of that, and it is still referring to old Activity. So, when user thread try to access any members of the old Activity, crashes will happen as the Activity already being destroyed. What is the best practice to overcome this?
The best way to overcome this is to use an
AsyncTaskinstead. If theActivityis destroyed while the task is executing, theAsyncTask(and its underlyingThreadthat is performing the operation) will continue its execution untildoInBackground()has completed. If theActivityisnullby the timeonPostExecuteis called, you won’t run into anyNullPointerExceptions for the reasons stated in this blog post.If you want to immediately cancel the task if the user “backs out” of the
Activity, you can callmTask.cancel()on yourAsyncTaskin yourActivity‘sonDestroymethod.If you don’t want to immediately cancel the task if the user “backs out” of the
Activity, then your long-term operation doesn’t sound like it is specific to anyActivityinstance. In this situation, it is often advised to use aServiceinstead.