Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Step #1: Make your <code>AsyncTask</code> a <code>static</code> nested class, or an entirely separate class, just not an inner (non-static nested) class.</p> <p>Step #2: Have the <code>AsyncTask</code> hold onto the <code>Activity</code> via a data member, set via the constructor and a setter.</p> <p>Step #3: When creating the <code>AsyncTask</code>, supply the current <code>Activity</code> to the constructor.</p> <p>Step #4: In <code>onRetainNonConfigurationInstance()</code>, return the <code>AsyncTask</code>, after detaching it from the original, now-going-away activity.</p> <p>Step #5: In <code>onCreate()</code>, if <code>getLastNonConfigurationInstance()</code> is not <code>null</code>, cast it to your <code>AsyncTask</code> class and call your setter to associate your new activity with the task.</p> <p>Step #6: Do not refer to the activity data member from <code>doInBackground()</code>.</p> <p>If you follow the above recipe, it will all work. <code>onProgressUpdate()</code> and <code>onPostExecute()</code> are suspended between the start of <code>onRetainNonConfigurationInstance()</code> and the end of the subsequent <code>onCreate()</code>.</p> <p><a href="http://github.com/commonsguy/cw-android/tree/master/Rotation/RotationAsync/" rel="noreferrer">Here is a sample project</a> demonstrating the technique.</p> <p>Another approach is to ditch the <code>AsyncTask</code> and move your work into an <code>IntentService</code>. This is particularly useful if the work to be done may be long and should go on regardless of what the user does in terms of activities (e.g., downloading a large file). You can use an ordered broadcast <code>Intent</code> to either have the activity respond to the work being done (if it is still in the foreground) or raise a <code>Notification</code> to let the user know if the work has been done. <a href="http://commonsware.com/blog/2010/08/11/activity-notification-ordered-broadcast.html" rel="noreferrer">Here is a blog post</a> with more on this pattern.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload