Android 内存回收机制:回收Activity,还是杀掉Pr

2016-09-11  本文已影响632人  zoudaokou2006

Android在内存不足的时候,会进行内存回收。
内存回收时,具体做了什么呢?

Andriod的官方文档

根据安卓官方文档

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish() method), or simply killing its process.

当内存不足时,系统有两种处理策略,
1)杀掉处于Paused状态或Stoped状态的Activity,
2)或者简单干脆点,直接杀掉该Activity所在的Process.

安卓核心工程师Dianne Hackborn的说法

在2011年,安卓核心团队工程师Dianne Hackborn表示:
(参考http://stackoverflow.com/questions/7536988/android-app-out-of-memory-issues-tried-everything-and-still-at-a-loss#comment56916204_7536988](http://stackoverflow.com/questions/7536988/android-app-out-of-memory-issues-tried-everything-and-still-at-a-loss#comment56916204_7536988 中hackbod的回答)

The only memory management that impacts activity lifecycle is the global memory across all processes, as Android decides that it is running low on memory and so need to kill background processes to get some back.
If your application is sitting in the foreground starting more and more activities, it is never going into the background, so it will always hit its local process memory limit before the system ever comes close to killing its process. (And when it does kill its process, it will kill the process hosting all the activities, including whatever is currently in the foreground.)

Android并没实现第一种办法,Android并不会去杀掉一个单独的Activity,只会杀掉Process及该Process上的所有Activity。

结论

看起来,两者发生矛盾了,都是权威,这可真让人困惑,我们应该怎么理解这个问题呢?
其实,应该换一个思路理解这个问题,两者都是对的——官方文档描述了规范,而Hackborn描述了实现。
而这种矛盾反映了规范和实现的差异。虽然Android在官方规范中定了某种机制,但到了具体的Android版本上,并没有完全实现这种机制。但是,未来的Android版本很可能会加上这种机制。

我们应该做什么?

从应用开发工程师的角度,

补充

Dianne Hackborn是2011年在StackOverflow上表示“Android只支持全局性的进程回收,不支持Activity的单独回收”。但对于最新的Android究竟如何处理的,并没有在网上看到更详细的说明。
所以我感觉,还是按照官方文档来,但要注意一点:
很多时候,官方文档会告诉你,它可能做什么,但并不确保一定会做。

参考

上一篇 下一篇

猜你喜欢

热点阅读