Reputation: 42870
I have the following situation
Thread
) from an Activity
.Activity
was destroyed.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
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?
Upvotes: 2
Views: 165
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 NullPointerException
s 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