Search code examples
androidmultithreadingandroid-asynctaskorientation-changesandroid-configchanges

What is the common practice to handle relation between Activity and Thread


I have the following situation

  1. I spawn a long running user thread (Thread) from an Activity.
  2. I press soft back button. So, the Activity was destroyed.
  3. I launch the same Activity again. Note, the previous launched Thread is 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?


Solution

  • The best way to overcome this is to use an AsyncTask instead. If the Activity is destroyed while the task is executing, the AsyncTask (and its underlying Thread that is performing the operation) will continue its execution until doInBackground() has completed. If the Activity is null by the time onPostExecute is called, you won't run into any NullPointerExceptions 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 call mTask.cancel() on your AsyncTask in your Activity's onDestroy method.

    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 any Activity instance. In this situation, it is often advised to use a Service instead.