Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an activity is killed, does the AsyncTask live on?

Tags:

I think I know the answer to this, but does an AsyncTask continue to live on once its calling Activity has been finish()ed?

    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(), "Your data is processing.", Toast.LENGTH_LONG);
        finish();
    }

Edit: so far two different answers :)

like image 556
Brian D Avatar asked Mar 07 '11 22:03

Brian D


People also ask

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.

What is a relationship between the lifecycle of an AsyncTask & life cycle of an activity?

AsyncTask is not tied to the life cycle of the Activity. Then when the AsyncTask does complete, it updates the old activity instance rather the new activity.

When AsyncTask is executed it goes through what steps?

An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

Can an AsyncTask be executed in a worker Thread?

Just for the Record: If you start a AsyncTask outside the UI-Thread the onPreExecute will not be executed from the UI-Thread (but from the caller Thread). This will lead to an exception. However the onPostExecute Method will always be executed on the UI-Thread.


3 Answers

The AsyncTask is tied to a UI thread and if the Activity is finished the async task is canceled.

[update] - Hackbod's comment below is correct. It should be noted that AsyncTasks are meant to be short lived and as such not worry so much about this issue. An AsycTask is only truly gone when it is completed OR the process is killed which may or may not happen after finish is called.

like image 169
Andrew White Avatar answered Nov 08 '22 21:11

Andrew White


It keeps running until the onPostExecute finishes.

like image 40
yogsma Avatar answered Nov 08 '22 20:11

yogsma


I've experienced some weirdness with Async Tasks where if an activity is killed by the OS and when the app resumes, the AsyncTasks sometimes do not run at all. I am unsure why they get into this state. If you execute your AsyncTasks in your own executor thread, this does not happen. I might be running into some odd circumstance. Thought it might be useful to post here anyway :).

like image 38
dineth Avatar answered Nov 08 '22 21:11

dineth