android - 在 Galaxy Nexus 内存不足之前,系统未销毁 Activity

标签 android memory-management

我在某些设备(如 Galaxy Nexus)中遇到问题,如果您继续打开 Activity ,就会遇到内存不足错误。我以为我有一些内存泄漏会阻止收集 Activity ,但我找不到它。所以我写了这个小 Activity (纯粹为了测试目的。)

public class Test extends Activity {    
    private byte[] imageData = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Button iv = new Button(this);
            imageData = new byte[1024 * 1024 * 2];
            iv.setText("Open");
            iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            startActivity(new Intent(Test.this, Test.class));
                    }
            });
            setContentView(iv);
    }
}

基本上,它分配了 2MB 的内存,您可以打开同一 Activity 的另一个实例。在 Galaxy S 和 Kindle Fire 上,如果你一直打开,内存使用量会增加到一定程度,然后它会开始为新 Activity 销毁旧 Activity 。

但是在 Galaxy Nexus 上,它只会上升到 64MB 并因内存不足错误而崩溃。

那么关于 android 内存管理有什么我不知道的吗,或者这是某些设备上的错误?如果这是错误,我该如何解决?

谢谢。

最佳答案

我就此询问了 Dianne Hackborn(一位 Android 框架工程师),以下是她给出的建议:

The point at which old activities are destroyed is an arbitrary number, based on the total number of activities across the entire system. This has always been the case. Relying on activities being destroyed to reclaim memory like that is never going to be stable; the activity manager doesn't know anything about the amount of RAM in a process or the limit on its RAM or how much RAM a new activity is going to take to actually have an idea when it should try to destroy activities in each process.

换句话说:您不能依赖系统销毁 Activity 作为您自己的应用程序中的内存管理方式。您仍然需要节俭使用内存,并尽可能让您的 Activity 清理它们自己的内存使用量。

在这种情况下,一旦 onStop()onPause() 被调用,释放您的内存可能是明智的。

关于android - 在 Galaxy Nexus 内存不足之前,系统未销毁 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9171941/

相关文章:

java - 在java中读取格式化的文本文件

android - 在显示警告对话框 Android 时隐藏状态栏

android - 如何通过在 AnimatedBuilder 中点击来关闭带有可关闭小部件的项目?

c - 传递未初始化的变量使用 C 抛出错误

c++ - 这种类型的内存是在堆上还是在栈上分配的?

ruby - 在 Ruby 中删除类实例?

Android 设备 onConfigurationChanged 事件不处理方向

android - 更新 SDK 后,Pixel 启动器一直停止

c++ - 为什么变量的打印地址会在每次执行时打印随机值,即使它是 C 中的逻辑地址?

c - 从堆栈和堆中获取二维数组的函数