Android獲得全部進程信息,並獲得該進程使用的內存情況。
package linuxidc.process;
import java.util.List;
import android.os.Bundle;
import android.os.Debug.MemoryInfo;
import android.widget.TextView;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.textView);
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
String all = "";
try {
List<RunningAppProcessInfo> list = activityManager
.getRunningAppProcesses();
for (int i = 0; i < list.size(); i++) {
RunningAppProcessInfo p = list.get(i);
String info = "第 " + (i + 1) + " 個進程\n";
info += "名稱:" + p.processName + "\n";
info += "id:" + p.pid + "\n";
info += "用戶id:" + p.uid + "\n";
// 該進程使用的內存情況,MemoryInfo單位是KB
int[] memoryPid = new int[] { p.pid };
MemoryInfo[] memoryInfo = activityManager
.getProcessMemoryInfo(memoryPid);
// 進程內存使用情況,單位:MB
int memSize = memoryInfo[0].dalvikPrivateDirty;
String count = "";
if (memSize < 1024)
count = memSize + " KB";
else
count = memSize / 1024 + " MB";
info += "使用的內存(dalvikPrivateDirty): " + count + "\n";
info += "重要級:" + p.importance + "\n";
all = all + info + "\n";
}
} catch (Exception e) {
e.printStackTrace();
}
tv.setText(all);
}
}
需要在AndroidManifest.xml添加權限:
<uses-permission android:name="android.permission.GET_TASKS" />
MainActivity.java需要的activity_main.xml文件:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11