Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to running AsyncTasks when the Activity changes?

While Network Operation is running in Asynctask, If user press the Back button and switch to another activity what will happen to Asynctask which is running in background?

  1. AsyncTask Process automatically Kill by OS?

  2. Async Task complete it's entire operation?

like image 912
Hardik Gajera Avatar asked Jun 27 '15 05:06

Hardik Gajera


Video Answer


3 Answers

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.

Similarly if user navigate to another activity,current activity will be destroyed or go in background activity stack and new activity would be in foreground.

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. Indeed it updates the former instance of the activity that is not displayed anymore. This can lead to an Exception of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity.

like image 155
Giru Bhai Avatar answered Sep 22 '22 10:09

Giru Bhai


AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.

1. AsyncTask processes are not automatically killed by the OS. AsyncTask processes run in the background and is responsible for finishing it's own job in any case. You can cancel your AsycnTask by calling cancel(true) method. This will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns.

2. After completion of it's operation, the background thread it's working on is stopped. AsyncTask has an onPostExecute() which is called once your work is finished. This method is called after doInBackground() method completes processing. Result from doInBackground() is passed to this method.

like image 24
capt.swag Avatar answered Sep 23 '22 10:09

capt.swag


AsyncTask will still run and try to post result on Zombie Activity. Best is to user AsyncTaskLoader.

like image 25
Wasim Avatar answered Sep 20 '22 10:09

Wasim