萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 安卓開發 >> Android 獲取進程內存使用情況方法

Android 獲取進程內存使用情況方法

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<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();

Map<Integer, String> pidMap = new TreeMap<Integer, String>();
for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
{
    pidMap.put(runningAppProcessInfo.pid, runningAppProcessInfo.processName);
}

Collection<Integer> 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");
    }
}

在看到上述代碼之前,自己按照API說明也寫了類似代碼如下,包含了更多的輸出參數。如果要檢查其他進程的內存使用情況,可略去循環中的條件判斷。按stackoverflow.com中帖子的說法 Pss的值是最能表明進程使用內存狀況

public long getmem_SELF() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningAppProcessInfo> procInfo = am.getRunningAppProcesses();
        for (RunningAppProcessInfo runningAppProcessInfo : procInfo) {  
        	System.out.println(runningAppProcessInfo.processName+ String.format
(",pid = %d", runningAppProcessInfo.pid));  
        	if( runningAppProcessInfo.processName.indexOf(this.getPackageName()) != -1 )
        	{
        		int pids[] = {runningAppProcessInfo.pid};
        		Debug.MemoryInfo self_mi[] = am.getProcessMemoryInfo(pids);
        		StringBuffer  strbuf = new StringBuffer();
        		strbuf.append(" proccess Name:").append(runningAppProcessInfo.processName)
        			.append("n pid:").append(runningAppProcessInfo.pid)
        			.append("n dalvikPrivateDirty:").append(self_mi[0].dalvikPrivateDirty)
	    	.append("n dalvikPss:").append(self_mi[0].dalvikPss)
	    	.append("n dalvikSharedDirty:").append(self_mi[0].dalvikSharedDirty)
	    	.append("n nativePrivateDirty:").append(self_mi[0].nativePrivateDirty)
	    	.append("n nativePss:").append(self_mi[0].nativePss)
	    	.append("n nativeSharedDirty:").append(self_mi[0].nativeSharedDirty)
	    	.append("n otherPrivateDirty:").append(self_mi[0].otherPrivateDirty)
	    	.append("n otherPss:").append(self_mi[0].otherPss)
	    	.append("n otherSharedDirty:").append(self_mi[0].otherSharedDirty)
	    	.append("n TotalPrivateDirty:").append(self_mi[0].getTotalPrivateDirty())
	    	.append("n TotalPss:").append(self_mi[0].getTotalPss())
	    	.append("n TotalSharedDirty:").append(self_mi[0].getTotalSharedDirty());
        		Log.v("TEST",strbuf.toString());
        	}
	}
<div class="dp-highlighter bg_java"><div class="bar">
<div class="tools"><b>[java]</b> <a href="#" class="ViewSource" title="view plain"
 onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">
view plain</a><a href="#" class="CopyToClipboard" title="copy
 onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">
copy</a><a href="#" class="PrintSource" title="print" 
onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a><a href="#"
 class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a>
<div style="position: absolute; left: 0px; top: 0px; width: 0px; height: 0px; z-index: 99; ">
<embed id="ZeroClipboardMovie_3" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf"
 loop="false" menu="false" quality="best" bgcolor="#ffffff" 
width="0" height="0" name="ZeroClipboardMovie_3" align="middle" allowscriptaccess="always" allowfullscreen="false"
 type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"
 flashvars="id=3&width=0&height=0" wmode="transparent">
</div>
</div>
</div>
<ol start="1" class="dp-j"><li class="alt"><span><span class="keyword">return</span>
<span> </span>
<span class="number">0</span><span>; 
</span></span></li><li class=""><span>  
</span></li></ol></div><pre name="code" class="java" style="display: none; ">
	return 0;
} </pre>
<pre></pre>
<br>
<p>翻譯:"Pss", "PrivateDirty"和 "SharedDirty"有什麼區別</p>
<p>  Android(亦即Linux)中,大量內存實際由多個進程共享,所以一個進程實際占用多少內存並不明確。甚至不太清楚哪些分頁被添加到磁盤。</p>
<p>   這樣,要是你要獲取所有實際映射在每個進程的物理內存值,然後試圖加總求和,你可能會得到一個遠大於實際內存總量的值。</p>
<p>   Pss是考慮共享內存的內核計算尺度 -- 基本上一個進程的每個內存頁面被按一個比率縮減,這個比率和同樣使用該頁面的其他進程的數量有關。
理論上你可以累計所有進程的Pss占用量來檢查所有進程的內存占用量,也可以比較進程的Pss來大致發現進程各自的權重。</p>
<p>   另一個有趣的參數是PrivateDirty,它基本上是進程內不能被分頁到磁盤的內存,也不和其他進程共享。查看進程的內存用量的另一個途徑,
就是當進程結束時刻,系統可用內存的變化情況(也可能會很快並入高速緩沖或其他使用該內存區的進程,
[<img alt="微笑" src="http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif">這樣一來,企圖就落空了:-)])
。<br>
</p>
<p>原文<br>
</p>
<p>But as to what the difference is between "Pss", "PrivateDirty", and "SharedDirty"... well now the fun begins.</p>
<p>A lot of memory in Android (and Linux systems in general)
 is actually shared across multiple processes. So how much memory 
a processes uses is really not clear. Add on top of that paging out to disk
 (let alone swap which we don't use on Android) and it is
 even less clear.</p>
<p>Thus if you were to take all of the physical RAM actually mapped in to each process, 
and add up all of the processes, you would probably end up with a number much greater than the actual total RAM.</p>
<p>The Pss number is a metric the kernel computes that takes into account memory sharing -- basically
 each page of RAM in a process is scaled by a ratio of the number of other processes
 also using that page. This way you can (in theory) add up the pss across
						
copyright © 萬盛學電腦網 all rights reserved