How do I discover memory usage of my application in Android?

前端 未结 9 2297
清酒与你
清酒与你 2020-11-21 06:27

How can I find the memory used on my Android application, programmatically?

I hope there is a way to do it. Plus, how do I get the free memory of the phone too?

9条回答
  •  囚心锁ツ
    2020-11-21 06:44

    This is a work in progress, but this is what I don't understand:

    ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
    MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(memoryInfo);
    
    Log.i(TAG, " memoryInfo.availMem " + memoryInfo.availMem + "\n" );
    Log.i(TAG, " memoryInfo.lowMemory " + memoryInfo.lowMemory + "\n" );
    Log.i(TAG, " memoryInfo.threshold " + memoryInfo.threshold + "\n" );
    
    List runningAppProcesses = activityManager.getRunningAppProcesses();
    
    Map pidMap = new TreeMap();
    for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
    {
        pidMap.put(runningAppProcessInfo.pid, runningAppProcessInfo.processName);
    }
    
    Collection keys = pidMap.keySet();
    
    for(int key : keys)
    {
        int pids[] = new int[1];
        pids[0] = key;
        android.os.Debug.MemoryInfo[] memoryInfoArray = activityManager.getProcessMemoryInfo(pids);
        for(android.os.Debug.MemoryInfo pidMemoryInfo: memoryInfoArray)
        {
            Log.i(TAG, String.format("** MEMINFO in pid %d [%s] **\n",pids[0],pidMap.get(pids[0])));
            Log.i(TAG, " pidMemoryInfo.getTotalPrivateDirty(): " + pidMemoryInfo.getTotalPrivateDirty() + "\n");
            Log.i(TAG, " pidMemoryInfo.getTotalPss(): " + pidMemoryInfo.getTotalPss() + "\n");
            Log.i(TAG, " pidMemoryInfo.getTotalSharedDirty(): " + pidMemoryInfo.getTotalSharedDirty() + "\n");
        }
    }
    

    Why isn't the PID mapped to the result in activityManager.getProcessMemoryInfo()? Clearly you want to make the resulting data meaningful, so why has Google made it so difficult to correlate the results? The current system doesn't even work well if I want to process the entire memory usage since the returned result is an array of android.os.Debug.MemoryInfo objects, but none of those objects actually tell you what pids they are associated with. If you simply pass in an array of all pids, you will have no way to understand the results. As I understand it's use, it makes it meaningless to pass in more than one pid at a time, and then if that's the case, why make it so that activityManager.getProcessMemoryInfo() only takes an int array?

提交回复
热议问题