装载机的生命周期是什么?

时间:2015-03-19 15:30:56

标签: android android-asynctask loader asynctaskloader

背景

我正在通过支持其横向模式来改善应用程序。我经常使用的一件事是Loaders,或者更具体地说是AsyncTaskLoaders

使用加载程序允许您继续执行后台任务,即使由于方向更改而重新创建活动,而不是AsyncTask

问题

我想问一下装载机的生命周期:

  1. 他们什么时候进行GC编辑?我是否必须跟踪它们,如果内部有位图,我应该尽快放弃它吗?他们可能只是在活动被真正销毁之后才进行GC编辑(而不是因为配置更改)?
  2. 我注意到他们有被停止的状态。这会以某种方式让我暂停吗?
  3. 如果#2为真,我如何实现一个可以暂停某些点的加载器?
  4. 碎片还有装载机吗?正如我所注意到的,它只适用于活动。
  5. 如果#4为假,在导航抽屉的设计模式中使用加载器的建议方法是什么,以取代容器中的碎片?
  6. AsyncTaskLoader可以像AsyncTask(或线程)一样被中断吗?我查看了它的代码和API,但我找不到它。我也试图找到一种解决方法,但我没有成功。
  7. 如果#6是假的,还有其他选择吗?例如,如果我知道加载器不需要加载某些东西,我可以立即停止它。我能想到的一种方法是设置一个标志(可能是AtomicBoolean,以防万一),它会告诉它停止,有时会检查这个值。问题是我甚至需要在它使用的函数内添加它,而更简单的方法是调用“Thread.sleep(0)”或类似的东西。
  8. 是否有某处解释装载机的生命周期?
  9. AsyncTaskLoaders是同时一起工作,还是像AsyncTask的默认当前行为一样,只在一个线程上运行?

1 个答案:

答案 0 :(得分:2)

1.When do they get GC-ed ? Do I have to keep track of them, and if one has a bitmap inside, should I abandon it as soon as possible? Do they perhaps get GC-ed only after the activity is really destroyed (and not because of configuration changes) ?

由于loader lifecycle与活动/片段生命周期相关联,因此可以安全地假设垃圾收集几乎同时发生。看一下#8的装载机生命周期。可能会给你一些想法。

2.I've noticed they have states of being stopped. Does this somehow allow me to pause them?

不,据我所知,装载者每次说话都没有onPause()

3.If #2 is true, How would I implement a loader that can be paused on some points of itself?

我真的没有回答这个问题。我想知道解决方案。

4.Can fragments also have Loaders? As I've noticed, it's only for activities.

当然片段可以有加载器。只需初始化loaderManager方法中的onActivityCreated()

即可
5.if #4 is false, what is the recommended way to use loaders in the design pattern of navigation-drawer that replaces fragments in the container?

4是真的。所以我猜这个问题无关紧要。

6.Can AsyncTaskLoader be interrupted like AsyncTask (or threads)? I've looked at its code and at the API, but I can't find it. I've also tried to find a workaround, but I didn't succeed.

我不确定你是什么意思打断装载机。但如果您的意思是与isCancelled()方法类似,那么cancelLoad()上会有一个名为AsyncTaskLoader的方法。完整的流程就像cancelLoad() - > cancel() - > onCancelled()我认为。

7.If #6 is false, is there an alternative? For example, if I know that the loader doesn't need to load something, I could just stop it right away. One way I can think of is to set a flag (maybe AtomicBoolean, just in case) that will tell it to stop, and check this value sometimes within. Problem is that I will need to add it even inside functions that it uses, while an easier way would be to call "Thread.sleep(0)" or something like that.

再次无关紧要?

9.Do AsyncTaskLoaders work together, at the same time, or are they like the default, current behavior of AsyncTask, which runs only on a single thread ?

在单个线程上运行。

8.Is there somewhere an explanation of the lifecycle of Loaders?

据我所知:

  • 当创建活动/片段时,加载器开始 - > onStartLoading()

  • 当活动变得不可见或片段被分离时,加载器停止 - > onStopLoading()

  • 重新创建活动或片段时无回调。 LoaderManager将结果存储在本地缓存中。

  • 当活动/片段被破坏时 - >调用restartLoader()destroyLoader()并重置加载程序。

我希望这会有所帮助。对于一些答案,我可能有点偏僻。我自己不断学习新事物。 欢呼声。