Android 生命周期内存管理

发布于 2024-10-08 00:26:40 字数 312 浏览 2 评论 0原文

我正在尝试确定如何在各种 Android 生命周期条件下保持我的应用程序的安全,例如另一个应用程序正在启动、手机进入睡眠状态等。我了解生命周期状态和我可以挂钩的事件方法,但我不确定如何处理我已经参考过的事物的记忆。我很清楚,如果操作系统需要,我的应用程序可能会随时被终止,但是个人引用呢?以下是一些示例场景:如果我的应用程序正在运行并且用户接到电话,或者用户启动另一个应用程序,或者手机进入睡眠状态。假设我的应用程序没有被杀死,我可以安全地使用我的引用还是会得到随机的空指针?我想这归结为...... Android 是否杀死或不杀死应用程序,或者它会从应用程序中回收一些内存(仍然存在有效的引用)而不杀死它?

I am trying to determine how to keep my app safe under various Android lifecycle conditions, such as another app being start, phone going to sleep, etc. I understand the lifecycle states and the event methods I can hook into, but I am not sure how memory is handled in regard to things I already had references to. I am well aware that my app may be killed at any time if the OS needs to, but what about individual references? Here are a few example scenarios: if my app is running and the user gets a phone call, or the user starts another app, or the phone goes to sleep. Assuming my app did not get killed, can I safely use my references or will I get random null pointers? I guess what this comes down to is... does Android either kill or not kill and app or will it reclaim some memory (where there are still valid references) from an app without killing it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最冷一天 2024-10-15 00:26:40

大多数时候,当用户切换到另一个应用程序或接听电话时,您的应用程序将被挂起。当它返回时,onResume() 将被调用,并且它将继续正常运行,不会出现任何问题。参考文献之类的应该没问题。不过,建议您取消注册侦听器并在 onResume() 中重新注册它们。

您应该永远记住,您的应用程序也可能随时被完全杀死,因此请保存您的数据。

Most of the time when the user switches to another app or answers the phone, you app will simply be suspended. When it comes back, onResume() will be called and it will continue on it's way with no issues. References and that kind of thing should be fine. It is recommended that you unregister listeners and re-register them in onResume(), though.

You should always remeber that your app may also be completely killed at any time, so save your data.

梦里梦着梦中梦 2024-10-15 00:26:40

事实上,大多数时候应用程序不会在短暂的中断(例如电话或电子邮件)中被终止,但如果您想支持这些情况,您应该在 onPause() 中执行清理或保存数据>。当应用程序返回时,它将执行onResume()

引用不会消失,直到activity被销毁,不用担心暂停中的NPE ->恢复场景,除非你正在做一些非常奇怪的事情。

如果您正在使用侦听器或 GPS,则应在 onPause() 期间取消注册并稍后恢复。

The truth is most of the time the application will not get killed in a brief interruption, for example a call or email, but if you want support these situations you should preform cleanup or saving the data in onPause(). When the application comes back it will execute onResume().

References will not disappear until the activity is destroyed, do not worry about NPE in the pause -> resume scenario unless you are doing something very odd.

If you are using listeners or GPS, you should unregister during onPause() and resume it later.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文