博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
手机安全卫士——进程管理
阅读量:6201 次
发布时间:2019-06-21

本文共 17718 字,大约阅读时间需要 59 分钟。

首先看一下界面:

TaskManagerActivity .java
//進程管理public class TaskManagerActivity extends Activity {    @ViewInject(R.id.tv_task_process_count)    private TextView tv_task_process_count;    @ViewInject(R.id.tv_task_memory)    private TextView tv_task_memory;    @ViewInject(R.id.list_view)    private ListView list_view;    private long totalMem;    private List
taskInfos; private List
userTaskInfos; private List
systemAppInfos; private TaskManagerAdapter adapter; private int processCount; private long availMem; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); initUI(); initData(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if(adapter != null){ adapter.notifyDataSetChanged(); } } private class TaskManagerAdapter extends BaseAdapter { @Override public int getCount() { //判断当前用户是否需要显示系统进程,需要就显示,不需要就不显示 boolean result = SharedPreferencesUtils.getBoolean(TaskManagerActivity.this, "is_show_system", false); if(result){ return userTaskInfos.size() + 1 + systemAppInfos.size() + 1; }else{ return userTaskInfos.size() + 1; } } @Override public Object getItem(int position) { if (position == 0) { return null; } else if (position == userTaskInfos.size() + 1) { return null; } TaskInfo taskInfo; if (position < (userTaskInfos.size() + 1)) { // taskInfo = userTaskInfos.get(position - 1); } else { // int location = position - 1 - userTaskInfos.size() - 1; taskInfo = systemAppInfos.get(location); } return taskInfo; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position == 0) { // TextView tv = new TextView(getApplicationContext()); tv.setBackgroundColor(Color.GRAY); tv.setTextColor(Color.WHITE); tv.setText("用户进程:" + userTaskInfos.size() + "个"); return tv; } else if (position == (userTaskInfos.size() + 1)) { TextView tv = new TextView(getApplicationContext()); tv.setBackgroundColor(Color.GRAY); tv.setTextColor(Color.WHITE); tv.setText("系统进程" + systemAppInfos.size() + "个"); return tv; } ViewHolder holder; View view; if (convertView != null && convertView instanceof LinearLayout) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = View.inflate(TaskManagerActivity.this, R.layout.item_task_manager, null); holder = new ViewHolder(); holder.iv_app_icon = (ImageView) view .findViewById(R.id.iv_app_icon); holder.tv_app_name = (TextView) view .findViewById(R.id.tv_app_name); holder.tv_app_memory_size = (TextView) view .findViewById(R.id.tv_app_memory_size); holder.tv_app_status = (CheckBox) view .findViewById(R.id.tv_app_status); view.setTag(holder); } TaskInfo taskInfo; if (position < (userTaskInfos.size() + 1)) { // taskInfo = userTaskInfos.get(position - 1); } else { // int location = position - 1 - userTaskInfos.size() - 1; taskInfo = systemAppInfos.get(location); } holder.iv_app_icon.setImageDrawable(taskInfo.getIcon()); holder.tv_app_name.setText(taskInfo.getAppName()); holder.tv_app_memory_size.setText("占用内存:" + Formatter.formatFileSize(TaskManagerActivity.this, taskInfo.getMemorySize())); if (taskInfo.isChecked()) { holder.tv_app_status.setChecked(true); } else { holder.tv_app_status.setChecked(false); } // if(taskInfo.getPackageName().equals(getPackageName())){ // holder.tv_app_status.setVisibility(View.INVISIBLE); }else{ // holder.tv_app_status.setVisibility(View.VISIBLE); } return view; } } static class ViewHolder { ImageView iv_app_icon; TextView tv_app_name; TextView tv_app_memory_size; CheckBox tv_app_status; } private void initData() { new Thread() { public void run() { taskInfos = TaskInfoParser .getTaskInfos(TaskManagerActivity.this); userTaskInfos = new ArrayList
(); systemAppInfos = new ArrayList
(); for (TaskInfo taskInfo : taskInfos) { if (taskInfo.isUserApp()) { userTaskInfos.add(taskInfo); } else { systemAppInfos.add(taskInfo); } } runOnUiThread(new Runnable() { @Override public void run() { adapter = new TaskManagerAdapter(); list_view.setAdapter(adapter); } }); }; }.start(); } private void initUI() { setContentView(R.layout.activity_task_manager); ViewUtils.inject(this); //SystemInfoUtils下文定义 processCount = SystemInfoUtils.getProcessCount(this); tv_task_process_count.setText("运行中进程:" + processCount + "个"); availMem = SystemInfoUtils.getAvailMem(this); totalMem = SystemInfoUtils.getTotalMem(this); tv_task_memory.setText("剩余/总内存:" + Formatter.formatFileSize(TaskManagerActivity.this, availMem) + "/" + Formatter.formatFileSize(TaskManagerActivity.this, totalMem)); list_view.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView
parent, View view, int position, long id) { // Object object = list_view.getItemAtPosition(position); if (object != null && object instanceof TaskInfo) { TaskInfo taskInfo = (TaskInfo) object; ViewHolder holder = (ViewHolder) view.getTag(); if(taskInfo.getPackageName().equals(getPackageName())){ return; } if (taskInfo.isChecked()) { taskInfo.setChecked(false); holder.tv_app_status.setChecked(false); } else { taskInfo.setChecked(true); holder.tv_app_status.setChecked(true); } } } }); } /** * 全选 * * @param view */ public void selectAll(View view) { for (TaskInfo taskInfo : userTaskInfos) { if (taskInfo.getPackageName().equals(getPackageName())) { continue; } taskInfo.setChecked(true); } for (TaskInfo taskInfo : systemAppInfos) { taskInfo.setChecked(true); } // 数据发生变化,一定要更新 adapter.notifyDataSetChanged(); } /** * 反选 * * @param view */ public void selectOppsite(View view) { for (TaskInfo taskInfo : userTaskInfos) { if (taskInfo.getPackageName().equals(getPackageName())) { continue; } taskInfo.setChecked(!taskInfo.isChecked()); } for (TaskInfo taskInfo : systemAppInfos) { taskInfo.setChecked(!taskInfo.isChecked()); } adapter.notifyDataSetChanged(); } /** * 清理 * * @param view */ public void killProcess(View view) { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List
killLists = new ArrayList
(); //清理的总共进程个数 int totalCount = 0; // 释放多少内存 int killMem = 0; for (TaskInfo taskInfo : userTaskInfos) { if (taskInfo.isChecked()) { killLists.add(taskInfo); // userTaskInfos.remove(taskInfo); totalCount++; killMem += taskInfo.getMemorySize(); } } for (TaskInfo taskInfo : systemAppInfos) { if (taskInfo.isChecked()) { killLists.add(taskInfo); // systemAppInfos.remove(taskInfo); totalCount++; killMem += taskInfo.getMemorySize(); // activityManager.killBackgroundProcesses(taskInfo .getPackageName()); } } /** * 当集合在迭代的时候,不能修改集合的大小 */ for (TaskInfo taskInfo : killLists) { //判断是否是用户app if (taskInfo.isUserApp()) { userTaskInfos.remove(taskInfo); // activityManager.killBackgroundProcesses(taskInfo .getPackageName()); } else { systemAppInfos.remove(taskInfo); // activityManager.killBackgroundProcesses(taskInfo .getPackageName()); } } UIUtils.showToast( TaskManagerActivity.this, "共清理" + totalCount + "个进程,释放" + Formatter.formatFileSize(TaskManagerActivity.this, killMem) + "内存"); //processCount //totalCount processCount -= totalCount; tv_task_process_count.setText("运行中的进程:"+ processCount +"个"); // tv_task_memory.setText("剩余/总内存:" + Formatter.formatFileSize(TaskManagerActivity.this, availMem + killMem) + "/" + Formatter.formatFileSize(TaskManagerActivity.this, totalMem)); // 刷新界面 adapter.notifyDataSetChanged(); } /** *设置 * @param view */ public void openSetting(View view){ startActivity(new Intent(TaskManagerActivity.this,TaskManagerSettingActivity.class)); }}
TaskInfoParser.java
public class TaskInfoParser {    public static List
getTaskInfos(Context context) { PackageManager packageManager = context.getPackageManager(); List
TaskInfos = new ArrayList
(); // ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); // List
appProcesses = activityManager .getRunningAppProcesses(); for (RunningAppProcessInfo runningAppProcessInfo : appProcesses) { TaskInfo taskInfo = new TaskInfo(); // String processName = runningAppProcessInfo.processName; taskInfo.setPackageName(processName); try { MemoryInfo[] memoryInfo = activityManager .getProcessMemoryInfo(new int[]{runningAppProcessInfo.pid}); int totalPrivateDirty = memoryInfo[0].getTotalPrivateDirty() * 1024; taskInfo.setMemorySize(totalPrivateDirty); PackageInfo packageInfo = packageManager.getPackageInfo( processName, 0); Drawable icon = packageInfo.applicationInfo .loadIcon(packageManager); taskInfo.setIcon(icon); String appName = packageInfo.applicationInfo.loadLabel( packageManager).toString(); taskInfo.setAppName(appName); System.out.println("-------------------"); System.out.println("processName="+processName); System.out.println("appName="+appName); ////packageInfo.applicationInfo.flags //ApplicationInfo.FLAG_SYSTEM int flags = packageInfo.applicationInfo.flags; //ApplicationInfo.FLAG_SYSTEM if((flags & ApplicationInfo.FLAG_SYSTEM) != 0 ){ // taskInfo.setUserApp(false); }else{// taskInfo.setUserApp(true); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); // taskInfo.setAppName(processName); taskInfo.setIcon(context.getResources().getDrawable( R.drawable.ic_launcher)); } TaskInfos.add(taskInfo); } return TaskInfos; }}
UIUtils.java
public class UIUtils {    public static void showToast(final Activity context,final String msg){        if("main".equals(Thread.currentThread().getName())){            Toast.makeText(context, msg, 1).show();        }else{            context.runOnUiThread(new Runnable() {                @Override                public void run() {                    Toast.makeText(context, msg, 1).show();                }            });        }    }}
SystemInfoUtils.java
public class SystemInfoUtils {        public static boolean isServiceRunning(Context context, String className) {
/** *都是管理器 * * ActivityManager 活动(任务/进程)管理器 * * packageManager 包管理器 */ ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); //获取到手机上所有运行的进程 List
infos = am.getRunningServices(200); for (RunningServiceInfo info : infos) { String serviceClassName = info.service.getClassName(); if (className.equals(serviceClassName)) { return true; } } return false; } public static int getProcessCount(Context context) { //得到进程的个数 ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); List
runningAppProcesses = activityManager .getRunningAppProcesses(); return runningAppProcesses.size(); } public static long getAvailMem(Context context) { //剩余内存 ActivityManager activityManager = (ActivityManager) context .getSystemService(context.ACTIVITY_SERVICE); MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); //得到内存的基本信息 activityManager.getMemoryInfo(memoryInfo); return memoryInfo.availMem; } public static long getTotalMem(Context context) { //总内存 try { // /proc/meminfo FileInputStream fis = new FileInputStream(new File("/proc/meminfo")); BufferedReader reader = new BufferedReader(new InputStreamReader( fis)); String readLine = reader.readLine(); StringBuffer sb = new StringBuffer(); for (char c : readLine.toCharArray()) { if (c >= '0' && c <= '9') { sb.append(c); } } return Long.parseLong(sb.toString()) * 1024; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; }}
TaskInfo.java  javabean
public class TaskInfo {        private Drawable icon;    private String packageName;        private String appName;        private long memorySize;        private boolean userApp;        private boolean checked;    public boolean isChecked() {        return checked;    }    public void setChecked(boolean checked) {        this.checked = checked;    }    public Drawable getIcon() {        return icon;    }    public void setIcon(Drawable icon) {        this.icon = icon;    }    public String getPackageName() {        return packageName;    }    public void setPackageName(String packageName) {        this.packageName = packageName;    }    public String getAppName() {        return appName;    }    public void setAppName(String appName) {        this.appName = appName;    }    public long getMemorySize() {        return memorySize;    }    public void setMemorySize(long memorySize) {        this.memorySize = memorySize;    }    public boolean isUserApp() {        return userApp;    }    public void setUserApp(boolean userApp) {        this.userApp = userApp;    }    @Override    public String toString() {        return "TaskInfo [packageName=" + packageName + ", appName=" + appName                + ", memorySize=" + memorySize + ", userApp=" + userApp + "]";    }      }

 SharedPreferencesUtils.java

public class SharedPreferencesUtils {    public static final String SP_NAME = "config";        public static void saveBoolean(Context context,String key , boolean value){        SharedPreferences sp = context.getSharedPreferences(SP_NAME, 0);        sp.edit().putBoolean(key, value).commit();    }        public static boolean getBoolean(Context context,String key,boolean defValue){        SharedPreferences sp = context.getSharedPreferences(SP_NAME, 0);        return sp.getBoolean(key, defValue);             }}

 

转载于:https://www.cnblogs.com/mengxiao/p/6379147.html

你可能感兴趣的文章
大一统的Netfilter-一种Linux防火墙优化方法
查看>>
Linux用户,组及权限管理
查看>>
Cisco asa5510 防火墙限制局域网内每个IP的速度
查看>>
HibernateException: No Session found for current thread
查看>>
OpenStack云平台的网络模式及其工作机制
查看>>
突破LVS瓶颈,LVS Cluster部署(OSPF + LVS)
查看>>
Java技术驿站
查看>>
为什么SQL Server数据文件和日志文件最后更新日期不准?
查看>>
dell服务器虚拟化平台应用【我身边的戴尔企业级解决方案】
查看>>
Freemarker 的 Eclipse 插件 安装
查看>>
84天平美女征婚【非诚勿扰】
查看>>
深入浅出之-route命令实战使用指南
查看>>
安装OpenStack ValueError: Tables "migrate_version" have non utf8 co
查看>>
后台登陆框post注入实战
查看>>
python安装pip (windows64)
查看>>
OEL6.1下oracle 11gr2 ASM安装
查看>>
Firewalld防火墙
查看>>
linux防火墙iptables详细教程
查看>>
通过swappiness内核参数调节swap使用
查看>>
【一天一个shell命令】好管家-查看当前登录用户-who
查看>>