【问题标题】:garbage collector and AsyncTask associated with the destroyed activity垃圾收集器和与被销毁活动关联的 AsyncTask
【发布时间】:2017-12-16 07:29:36
【问题描述】:

我正在阅读“android 最佳实践”一书。这让我对使用 AsyncTask 产生了疑问。

许多示例展示了如何在 Activity 中使用 AsyncTask 类来完成此任务。 虽然这种方法在大多数情况下都有效,但方向从纵向更改为横向或 反之亦然会产生意想不到的效果。创建 AsyncTask 的 Activity 被销毁 方向改变并以新方向重新创建。 AsyncTask 保持关联 与被破坏的活动,所以结果不能返回到新活动。此外,网络服务 在 AsyncTask 中的原始 Activity 中回调方法防止垃圾收集器 回收原始活动的内存,除非在活动时特别注意 被摧毁。使用 AsyncTask 有一些解决此问题的方法,但有更好的方法来解决 问题是使用 IntentService 类,因为它存在于 Activity 生命周期之外。

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

****************** 编辑 *******************

我的主要问题是:

1- Asynctask 的activity被销毁后如何销毁?

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

【问题讨论】:

标签: android android-activity android-asynctask


【解决方案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. 

【讨论】:

    【解决方案2】:

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

    答案 2:使用 retrofit,因为通过 AsyncTask 轻松设置和处理所有问题

    【讨论】:

      猜你喜欢
      • 2012-04-20
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      相关资源
      最近更新 更多