/**
* @param ctx 上下文环境
* @return 当前手机正在运行的进程的相关信息
*/
public static List<ProcessInfo> getProcessInfo(Context ctx){
//获取进程相关信息
List<ProcessInfo> processInfoList = new ArrayList<ProcessInfo>();
//1,activityManager管理者对象和PackageManager管理者对象
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
PackageManager pm = ctx.getPackageManager();
//2,获取正在运行的进程的集合
List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
//3,循环遍历上诉集合,获取进程相关信息(名称,包名,图标,使用内存大小,是否为系统进程(状态机))
for (RunningAppProcessInfo info : runningAppProcesses) {
ProcessInfo processInfo = new ProcessInfo();
//4,获取进程的名称 == 应用的包名
processInfo.packageName = info.processName;
//5,获取进程占用的内存大小(传递一个进程对应的pid数组)
android.os.Debug.MemoryInfo[] processMemoryInfo = am.getProcessMemoryInfo(new int[]{info.pid});
//6,返回数组中索引位置为0的对象,为当前进程的内存信息的对象
android.os.Debug.MemoryInfo memoryInfo = processMemoryInfo[0];
//7,获取已使用的大小
processInfo.memSize = memoryInfo.getTotalPrivateDirty()*1024;
try {
ApplicationInfo applicationInfo = pm.getApplicationInfo(processInfo.packageName, 0);
//8,获取应用的名称
processInfo.name = applicationInfo.loadLabel(pm).toString();
//9,获取应用的图标
processInfo.icon = applicationInfo.loadIcon(pm);
//10,判断是否为系统进程
if((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM){
processInfo.isSystem = true;
}else{
processInfo.isSystem = false;
}
} catch (NameNotFoundException e) {
//需要处理
processInfo.name = info.processName;
processInfo.icon = ctx.getResources().getDrawable(R.drawable.ic_launcher);
processInfo.isSystem = true;
e.printStackTrace();
}
processInfoList.add(processInfo);
}
return processInfoList;
}
public class ProcessInfo {
public String name;//应用名称
public Drawable icon;//应用图标
public long memSize;//应用已使用的内存数
public boolean isCheck;//是否被选中
public boolean isSystem;//是否为系统应用
public String packageName;//如果进程没有名称,则将其所在应用的包名最为名称
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public long getMemSize() {
return memSize;
}
public void setMemSize(long memSize) {
this.memSize = memSize;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}
public boolean isSystem() {
return isSystem;
}
public void setSystem(boolean isSystem) {
this.isSystem = isSystem;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
}