Android获得全部进程信息,并获得该进程使用的内存情况。
package zhangphil.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>
时间: 2024-10-10 21:58:49