Android获得全局进程信息以及进程使用的内存情况

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 专题页面 ?tid=11

本文永久更新链接地址

Java线程池:ExecutorService,Executors

Android通知Notification

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0778196383d822d6bf4848fc291bd586.html