What happens to running AsyncTasks when the Activity changes?

后端 未结 3 701
粉色の甜心
粉色の甜心 2020-12-16 11:55

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?

相关标签:
3条回答
  • 2020-12-16 12:27

    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.

    0 讨论(0)
  • 2020-12-16 12:36

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

    0 讨论(0)
  • 2020-12-16 12:39

    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.

    0 讨论(0)
提交回复
热议问题