是否可以使用超过最大 android 堆?

Is it possible to use more than maximum android heap?

如果单个应用程序只能使用 32mb 堆,为什么 android 设备需要 1 或 2gb RAM?我无法将大图像加载到 RAM 中,例如 3000x3000(它只有 34mb)。

可用,here,在 android 文档中,使用

android:largeHeap="true"

将允许您使用更大的堆大小,但建议您尽可能使用较小的映像。

Whether your application's processes should be created with a large Dalvik heap. This applies to all processes created for the application. It only applies to the first application loaded into a process; if you're using a shared user ID to allow multiple applications to use a process, they all must use this option consistently or they will have unpredictable results. Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.

To query the available memory size at runtime, use the methods getMemoryClass() or getLargeMemoryClass().

是的,这是真的。有些人可能会争辩说,这是为 Android 开发应用程序时面临的最大挑战之一,尤其是那些需要加载大图像的应用程序。

克服此问题的最佳方法是在使用 Android 应用程序时简单地接受此限制,并在创建位图时非常小心。原则上,内存中的位图永远不应超过屏幕上一次显示的数量。这意味着加载较小的位图,并回收不再使用的位图。

但是,有时您需要同时保存大量位图,而这个数量超出了每个应用程序的内存限制。

为此,最好的选择可能是将这些位图渲染为 OpenGL-ES 纹理。

当您在 Android 中使用 OpenGL-ES 时,纹理(本质上是位图的 OpenGL 名称)保存在设备的堆中,并且不受与普通位图相同的内存限制的限制。在这里,您可以充分利用设备 RAM。

OpenGL-ES 对于开发人员来说被认为是一个稍微 "advanced" 的主题,但是如果您遵循一些教程,例如 this one,您可以很快地设置一些基本的东西。

最后一点,您还可以在清单文件中定义 largeHeap="true"。这将为您的应用程序分配更多内存,但最终您会遇到与以前相同的问题 - 无法访问完整的设备内存。如果您只需要多一点内存,这是一个很好的解决方案,但如果您的内存需求非常大,那么它可能不够用。