首先也是要建立一个javabean
package com.itheima.bean; import android.graphics.drawable.Drawable; public class TaskInfo { private Drawable icon; private String name; private String size; private boolean isUser; public Drawable getIcon() { return icon; } public void setIcon(Drawable icon) { this.icon = icon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public boolean isUser() { return isUser; } public void setUser(boolean isUser) { this.isUser = isUser; } @Override public String toString() { return "TaskInfo [name=" + name + ", size=" + size + ", isUser=" + isUser + "]"; } }
然后通过activitymanager来获取运行中程序的list集合
通过遍历集合获得包名,
在通过packagemanager和包名来获得其他信息
package com.itheima.engine; import java.util.ArrayList; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.drawable.Drawable; import android.os.Debug.MemoryInfo; import android.text.format.Formatter; import com.itheima.bean.TaskInfo; import com.itheima.superman.R; public class TaskInfoProvider { private static String packageName; public static List<TaskInfo>getTaskInfo(Context context){ List<TaskInfo> list = new ArrayList<TaskInfo>(); ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); PackageManager pm = context.getPackageManager(); List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses(); for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) { TaskInfo task = null; try { task = new TaskInfo(); packageName = runningAppProcessInfo.processName; //得到图标 Drawable loadIcon = pm.getPackageInfo(packageName, 0).applicationInfo.loadIcon(pm); task.setIcon(loadIcon); //得到名称 task.setName(pm.getPackageInfo(packageName, 0).applicationInfo.loadLabel(pm).toString()); //是不是用户程序 int flag = pm.getPackageInfo(packageName, 0).applicationInfo.flags; if((flag&ApplicationInfo.FLAG_SYSTEM)==0){ task.setUser(true); }else{ task.setUser(false); } //得要程序占用运行内存 MemoryInfo processMemoryInfo = am.getProcessMemoryInfo(new int[]{runningAppProcessInfo.pid})[0]; String size = Formatter.formatFileSize(context, processMemoryInfo.getTotalPrivateDirty()*1024); task.setSize(size); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); //系统中有些程序是用C语言写的没有图标和名字 task.setIcon(context.getResources().getDrawable(R.drawable.ic_launcher)); task.setName(packageName); } list.add(task); } return list; } }