android - 确定 Activity 的可用堆空间(防止 OutOfMemoryException)

标签 android

我读过 How do I discover memory usage of my application in Android?和一堆其他答案,但不能完全确定...

我有一个 Activity,它会将文件从外部存储加载到内存中,并在内存中执行一些解析/操作/等操作。在我加载它之前,我想猜测这样做是否会导致 OutOfMemoryException 并使 Activity 崩溃(我知道不可能有确切的答案,估计总比没有好。)

根据上面链接的答案,我想出了:

ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);

int pid [] = {android.os.Process.myPid()};

android.os.Debug.MemoryInfo[] mi = activityManager.getProcessMemoryInfo(pid);

// calculate total_bytes_used using mi...

long available_bytes = activityManager.getMemoryClass()*1024*1024 - total_bytes_used;

所以,问题:

1)我疯了吗?
2) 如何将MemoryInfo 对象的值加总以估计 Activity/任务的堆使用情况? (上面的链接给出了 pss/private-dirty/shared-dirty 的概述,但没有足够的信息来猜测如何做总数。)
3)Debug是一直存在还是只在调试时存在?
4)有没有更聪明的方法?

像这样的答案:Two questions about max heap sizes and available memory in android似乎暗示没有比这更好的方法了?

我知道使用更少的内存是一件好事,我也是。我很想知道如何在这里进行防御性编码。只是等待异常才知道您的内存不足,这似乎很奇怪。

谢谢!

最佳答案

您可以引用此链接.. 对您面临的同一问题的完整研究。 OOMRESEACH

关于android - 确定 Activity 的可用堆空间(防止 OutOfMemoryException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5684461/

相关文章:

java - GZIP 压缩到字节数组

android - Android Studio编译错误

java - Android float 操作按钮未被识别

android - Android 上的 EventBus : how to implement dynamic queues vs. 基于类的事件订阅?

android - 如何在使用库的eclipse中导入android studio项目?

java - 打开 Android 图片库

java - 将字符串写入 Assets 文件夹中的文件

android - 80Mb mp3 文件+40MB 图像,什么是最好的地方? Assets 或原始?eclipse 需要时间来构建?(android 3.0)

android - ActiveAndroid:未创建日期列

android - Dagger,如何注入(inject)一个类,而不是一个模块