什么是获取我的应用程序的内存使用量的正确方法

时间:2019-01-10 14:46:30

标签: android memory

四处搜寻,但仍未得到明确的答案。 尝试了两种路由后,一种使用Debug.MemoryInfo(),另一种使用activityManager。似乎两者都获得了内存使用率,但有所不同

什么是检查应用程序内存使用情况的正确方法?

1返回49436(似乎在不同设备上更一致)

val appMemory: Double
get() {
    val memInfo = Debug.MemoryInfo()
    Debug.getMemoryInfo(memInfo)
    var res = memInfo.totalPrivateDirty.toDouble()

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        res += memInfo.totalPrivateClean.toDouble()

    return res
}

2返回113695 kb

fun otherMemoryFunc() {
    val context = this.context.applicationContext
    val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager ?: return

    ThreadPoolExecutorSingleton.getInstance().execute {
        val runningAppProcesses = activityManager.runningAppProcesses
        val it = runningAppProcesses.iterator()

        while (it.hasNext()) {
            val runningAppProcessInfo = it.next() as ActivityManager.RunningAppProcessInfo
            if (runningAppProcessInfo.processName == context.getPackageName()) {
                val pids = intArrayOf(runningAppProcessInfo.pid)
                val memoryInfo = activityManager.getProcessMemoryInfo(pids)

                if (memoryInfo != null && memoryInfo.isNotEmpty()) {

                    Log.i("+++", "+++ memoryInfo[0].totalPss: ${memoryInfo[0].totalPss}")

                } else {
                    Log.e("+++", "+++ !!! no memoryInfo")
                }
                break
            }
        }
    }
}

0 个答案:

没有答案