活动堆栈已满:OutOfMemoryError [英] Activity Stack full: OutOfMemoryError

查看:84
本文介绍了活动堆栈已满:OutOfMemoryError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

My App 设计有侧边菜单,因此基本上您可以从任何 Activity 启动任何 Activity.如果我以 Android 后退堆栈的默认行为启动 Activity,Activity 会相互堆叠,直到手机内存已满,这会导致非常可怕的

My App is designed with a side menu, so that basically you can start any Activity from any Activity. If I start the activity with the default behaviour of the back stack of Android, the Activities get stacked on each other until the memory of the phone is full and it results in a very scary

02-09 15:43:12.807 1860-1868/?E/System: java.lang.OutOfMemoryError: OutOfMemoryError 在尝试抛出 OutOfMemoryError 时抛出;没有可用的堆栈跟踪

02-09 15:43:12.807 1860-1868/? E/System: java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack trace available

现在我的问题是:

  1. 我是否应该使用另一种启动模式(REORDER_TO_FRONT、CLEAR_TOP)启动 Activity,但所有这些都会使后退按钮的行为变得更糟?
  2. 如果内存已满,GC 是否会真正收集一些活动,而我的问题是我可能只是有一些指向它们的强引用离开,使它们无法从内存中清除?

谁能解释一下,谢谢!

推荐答案

当一个 Activity 被放到后台堆栈时,Android 通常会将实例保存在内存中.当内存不足时,后台堆栈活动将关闭(这包括调用 onSaveInstanceState() onDestroy()),但系统会保留重新创建它们所需的信息,以防用户返回.
保留的信息很少,应该不会有问题,除非您堆叠了数百个活动.另一方面,Activity实例一旦被销毁,就永远不会被重用,必须是可垃圾回收的,否则构成Context泄漏,这可能不明显.

When an activity is put on the back stack, Android usually keeps the instance in memory. When the memory is low, back stack activities are shut down (this includes calling onSaveInstanceState() onDestroy()), but the system keeps the information needed to recreate them, in case the user navigates back.
The retained information is small and should not be a problem, unless you have hundred of activities stacked. On the other hand, once destroyed, the activity instance will never be reused and must be garbage-collectable, otherwise it constitutes a Context leaks, which mays not be obvious to spot.

一些建议:

  1. 启用 StrictMode 尤其是 detectActivityLeaks() 检测活动(和其他Android 的对象)泄漏

  1. Enable StrictMode and in particular detectActivityLeaks() to detect Activity (and other Android's objects) leaks

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectActivityLeaks()

        // or even
        .detectAll()

        .penaltyLog()
        // or
        .penaltyDeath()

        .build());        

  • 使用 Android Studio 的内存分析器.堆转储 可以显示引用的位置握住.较旧的内存监视器具有分析器任务来查找泄漏的活动.据我所知,Android Studio 3.0 中没有对应的

  • Use Android Studio's memory profiler. Heap dumps can show you where references are held. The older memory monitor had analyzer tasks to find leaked activities. As far as I know there is no equivalent in Android Studio 3.0

    尝试启用和不启用设备开发者选项中的不要保留活动选项.启用它会使活动生命周期更可预测.

    Try with and without enabling the Don't keep activities option in the device's developer options. Enabling it makes the activities lifecycle more predictable.

    使用像 LeakCanary

    这篇关于活动堆栈已满:OutOfMemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆