Android How to connect to AsyncTask after onDestroy () and restart onCreate ()?

I tested the expression that AsyncTasks are not destroyed along with their launch. And it is true .

I made AsyncTask post a message Log.i()every 3 seconds for 1 minute. And I put Log.i()messsage in the onDestroy()activity method .

I see that the activity is destroyed, but AsyncTask continues to work until it has finished all 20 Log.i()messages.

And I'm embarrassed.

  • What if AsyncTask has publishProgress()a ruined user interface?
    I guess some kind of exception will happen, right?

  • What if AsyncTask stores data in a global variable class Application?
    Don't know here, NullPointer exception?

  • What to do if the application rebooted?
    He will probably launch the new AsyncTask. Can it connect to AsyncTask still running?

  • Is AsyncTask immortal after destroying the parent application?
    Perhaps yes, as all LogCat applications preserve message logging when the user interface application is no longer visible, maybe it is destroyed? And when you open them again, they show you the disturbances that were created while they were "dead."

, . AsyncTask, , , , .

, . . , AsyncTask, . , , .

+5
1

, , - , ( IntentService, , ).

, , Activity...

public class MyMainActivity extends Activity {

    FileDownloader fdl = null;

    ...

    // This is an inner class of my main Activity
    private class FileDownloader extends AsyncTask<String, String, Boolean> {
        private MyMainActivity parentActivity = null;

        protected void setParentActivity(MyMainActivity parentActivity) {
            this.parentActivity = parentActivity;
        }

        public FileDownloader(MyMainActivity parentActivity) {
            this.parentActivity = parentActivity;
        }

      // Rest of normal AsyncTask methods here

    }
}

onRetainNonConfigurationInstance() AsyncTask.

Override
public Object onRetainNonConfigurationInstance() {

    // If it exists then we MUST set the parent Activity to null
    // before returning it as once the orientation re-creates the
    // Activity, the original Context will be invalid

    if (fdl != null)
        fdl.setParentActivity(null);
    return(fdl);
}

doDownload(), onResume(), a Boolean, downloadComplete, . Boolean onPostExecute(...) FileDownloader.

private void doDownload() {
    // Retrieve the FileDownloader instance if previousy retained
    fdl = (FileDownloader)getLastNonConfigurationInstance();

    // If it not null, set the Context to use for progress updates and
    // to manipulate any UI elements in onPostExecute(...)
    if (fdl != null)
        fdl.setParentActivity(this);
    else {
        // If we got here fdl is null so an instance hasn't been retained
        String[] downloadFileList = this.getResources().getStringArray(R.array.full_download_file_list);
        fdl = new FileDownloader(this);
        fdl.execute(downloadFileList);
    }
}
+1

All Articles