在过去几年中,为了检查Android上的堆内存量以及使用量,可以使用以下内容:
@JvmStatic
fun getHeapMemStats(context: Context): String {
val runtime = Runtime.getRuntime()
val maxMemInBytes = runtime.maxMemory()
val availableMemInBytes = runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory())
val usedMemInBytes = maxMemInBytes - availableMemInBytes
val usedMemInPercentage = usedMemInBytes * 100 / maxMemInBytes
return "used: " + Formatter.formatShortFileSize(context, usedMemInBytes) + " / " +
Formatter.formatShortFileSize(context, maxMemInBytes) + " (" + usedMemInPercentage + "%)"
}
Run Code Online (Sandbox Code Playgroud)
这意味着,您使用的内存越多,特别是通过将位图存储到内存中,您就可以越接近允许应用程序使用的最大堆内存.当您达到最大值时,您的应用程序将因OutOfMemory异常(OOM)而崩溃.
我注意到在Android O上(在我的情况下是8.1,但它也可能在8.0上),上面的代码不受Bitmap分配的影响.
进一步深入,我注意到在Android分析器中你使用的内存越多(在我的POC中保存大位图),使用的本机内存就越多.
为了测试它是如何工作的,我创建了一个简单的循环:
val list = ArrayList<Bitmap>()
Log.d("AppLog", "memStats:" + MemHelper.getHeapMemStats(this))
useMoreMemoryButton.setOnClickListener {
AsyncTask.execute {
for (i in …Run Code Online (Sandbox Code Playgroud)