android获取正在运行的进程

时间:2022-06-23 04:57:51

实体类

public class ProcessInfo {
public String name;
public String packageName;
public Drawable icon;
public long memory;
public boolean isUser; //true表示用户进程
public boolean isChecked; //表示当前item是否被勾选
}

获取正在运行的进程列表

public ArrayList<ProcessInfo> getRunningProcesses(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = am
.getRunningAppProcesses();//获取运行中进程集合

PackageManager pm = context.getPackageManager();
ArrayList<ProcessInfo> list = new ArrayList<ProcessInfo>();
for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
ProcessInfo info = new ProcessInfo();

String packageName = runningAppProcessInfo.processName; //包名
info.packageName = packageName;

int pid = runningAppProcessInfo.pid;
Debug.MemoryInfo[] processMemoryInfo = am.getProcessMemoryInfo(new int[]{pid});//根据pid返回内存信息
long memory = processMemoryInfo[0].getTotalPrivateDirty() * 1024; //获取当前进程占用内存大小
info.memory = memory;

try {
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);//根据包名获取相关应用的信息
String name = applicationInfo.loadLabel(pm).toString();
Drawable icon = applicationInfo.loadIcon(pm);

info.name = name;
info.icon = icon;

int flags = applicationInfo.flags;
if((flags & ApplicationInfo.FLAG_SYSTEM)==ApplicationInfo.FLAG_SYSTEM){
//系统进程
info.isUser = false;
}else{
//用户进程
info.isUser = true;
}

} catch (PackageManager.NameNotFoundException e) {
//某些系统进程没有名称和图标,会走此异常
info.name = packageName;
info.icon = context.getResources().getDrawable(R.drawable.system_default);
info.isUser = false;
e.printStackTrace();
}

list.add(info);
}

return list;
}