简体   繁体   中英

garbage collector and AsyncTask associated with the destroyed activity

i'm reading "android Best Practices"book. it make me a question about using AsyncTask.

Many examples show how to accomplish this using the AsyncTask class from within an Activity. While this approach will work most of the time, an orientation change from portrait to landscape or vice versa will have an unintended effect. The Activity that created the AsyncTask is destroyed on the orientation change and re-created in the new orientation. The AsyncTask remains associated with the destroyed activity, so the result cannot return to the new activity. Additionally, Web Services to callback methods in the original Activity in the AsyncTask prevent the garbage collector from reclaiming the memory of the original Activity unless special care is taken when the activity is destroyed. There are some solutions to this problem using AsyncTask, but a better way to solve the problem is to use an IntentService class because it lives outside the Activity lifecycle.

what is the solution for solving this problem? and Is the use of asynctask as correct? what is the best way for connecting to web service and get our data from it?

************* Edit *******************

my main question is:

1- how can destroy Asynctask when its activity is destroyed?

2- what is the best way for connecting to web service and get our data from it? intentService or AsyncTask or ... ?

 1. AsyncTasks don't follow Activity instances' life cycle. 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.

    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. intentService or AsyncTask or Volley or Retrofit , there are so many 
     way for connecting with web services and all has it's importance. But 
     you can use Volley is now officially supported by Google. 

answer 1: use activity.isFinishing() for checking finishing activity

answer 2: use retrofit because easy setup and handle all problem by AsyncTask

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM