垃圾收集器和与被破坏的活动相关联的AsyncTask

时间:2017-07-12 03:43:52

标签: android android-activity android-asynctask

我正在阅读“android Best Practices”一书。它让我对使用AsyncTask感到疑问。

许多示例显示如何使用Activity中的AsyncTask类来完成此操作。 虽然这种方法大部分时间都可以使用,但是从纵向到横向或方向的方向也会发生变化 反之亦然会产生意想不到的影响。创建AsyncTask的Activity将被销毁 方向改变并在新方向中重新创建。 AsyncTask保持关联 与被破坏的活动,因此结果无法返回到新活动。此外,Web服务 在AsyncTask中原始Activity中的回调方法阻止了垃圾收集器 回收原始活动的记忆,除非活动时特别小心 销毁。使用AsyncTask有一些解决这个问题的方法,但是有一个更好的解决方法 问题是使用IntentService类,因为它位于Activity生命周期之外。

解决这个问题的解决方案是什么?并且asynctask的使用是否正确? 连接到Web服务并从中获取数据的最佳方法是什么?

************* 修改 *******************

我的主要问题是:

1-如何在销毁活动时销毁Asynctask?

2-连接到Web服务并从中获取数据的最佳方式是什么? intentService或AsyncTask或......?

2 个答案:

答案 0 :(得分:1)

 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. 

答案 1 :(得分:0)

回答1:使用activity.isFinishing()检查完成活动

回答2:使用retrofit因为易于设置并处理AsyncTask的所有问题