Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42870

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

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?

Upvotes: 2

Views: 165

Answers (1)

Alex Lockwood
Alex Lockwood

Reputation: 83311

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.

Upvotes: 1

Related Questions