AsyncTask best practice is how to check if all activity is

After AsyncTask completes, I usually do one of the following:

  • Call the method for the callback object / interface that I define in action and go to the constructor of the My AsyncTask subclass.
  • Provide AsyncTask to the handler and call myHandler.sendMessage () when the task is complete.

I want to ask what is considered best practice after completing AsyncTask. If the user clicked the Home button during task processing, the activity is no longer in pre-order. As soon as the application tries to perform some user interface operation, the OS throws a WindowManager $ BadTokenException in response to the completion of the task.

I can of course surround my user interface code with catch for a BadTokenException. It seems hacked. Is there a way to find out if there is activity ahead?

+4
source share
4 answers

This means that you are using some where context is not appropriate. To resolve doubts about the exception, see this link. Bad Token exception

+1
source

You may not like my answer, but I find AsyncTask broken (for reasons like this).

Edit: My initial answer recommended using IntentService and translating the result. It is as inefficient as sending a letter to yourself.

You can use AsyncTaskLoader , which works around AsyncTask problems, but the AsyncTaskLoader API AsyncTaskLoader far from excellent. In particular, you must ensure that the bootloader identifier is unique, and keep in mind that the results are cached for the identifier and not for the arguments. In addition, the exception propagation is the same as with AsyncTask .

A more modern and safer way to solve the problem is to use the future of Guava .

+2
source

You can check whether it is active or not. I usually make my AsyncTask subclass static (to avoid memory leaks), so I pass an activity reference (wrapped in WeakReference to avoid memory leaks).

When onPostExecute is executed, I perform the necessary checks when using WeakReferences plus calling Activity.isFinishing () for the activity, so I can verify that the action is not being performed to avoid making user interface changes to the dying Activity.

+1
source

Define your activity object in your onStart () as a static member -

 private static MyActivity mActivity = null; public void onStart() { mActivity = this; } public void onDestroy() { mActivity = null; } 

Then in your AsyncTask method do the following:

 if (mActivity != null) { mActivity.doSomething(); //make sure to use static member } 
0
source

All Articles