手机安全卫士——进程管理

首先看一下界面:

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<TaskInfo> taskInfos;
    private List<TaskInfo> userTaskInfos;
    private List<TaskInfo> 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<TaskInfo>();

                systemAppInfos = new ArrayList<TaskInfo>();

                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<TaskInfo> killLists = new ArrayList<TaskInfo>();

        //清理的总共进程个数
        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<TaskInfo> getTaskInfos(Context context) {

        PackageManager packageManager = context.getPackageManager();

        List<TaskInfo> TaskInfos = new ArrayList<TaskInfo>();
        //
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(context.ACTIVITY_SERVICE);
        //
        List<RunningAppProcessInfo> 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<RunningServiceInfo> 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<RunningAppProcessInfo> 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 + "]";
    }
}
时间: 2024-10-18 03:29:31

手机安全卫士——进程管理的相关文章

手机安全卫士——软件管理-用户程序和系统程序

首先看一下界面: AppManagerActivity .java //软件管理 public class AppManagerActivity extends Activity implements View.OnClickListener{ List<AppInfo> appinfos; ListView lv; private List<AppInfo> userAppInfos; private List<AppInfo> systemAppInfos; pri

我的手机管家(2) 进程管理布局

我的手机管家(2)  进程管理 (1)获取进程信息:所有的进程信息, 正在运行的进程信息, 剩余可用内存 (2)获取进程信息是一个耗时的操作, 首先在使用子线程获取进程信息的时候显示缓冲界面,缓冲加载完成后, 通知LIstView展示数据,加载适配器, 同时缓冲结束 获取进程信息的提供者: package com.ejob.phonesafe.provider; import java.io.BufferedReader; import java.io.FileReader; import ja

手机卫士09_应用程序四种查看_ListView小标题_进程管理

1.悬浮窗体的功能实现: 1.1.应用程序的卸载: 包安装器 packageInstall,包卸载packageruninstall intent.setData(Uri.pare(“package:” + 应用程序包名)) 卸载完之后记得更新list集合,更新适配器. 但是不确定用户是否点了卸载,所以要通过广播获取消息. 并且需要通过代码注册,因为这个广播只在应用管理生效. 要记得addDataSchme(“package”) 接收完广播之后,更新了集合适配器,要记得关闭广播 异常:Concu

我的手机管家(4) 进程管理逻辑代码

本节主要介绍进程管理界面的逻辑代码:至此进程管理的功能已经完善了 首先要加载正在运行的进程,获取进程信息, 这是一个耗时的操作, 所以一个子线程来处理缓冲加载, 加载完数据就通知ListView 将数据展示到 界面,listview怎么知道,数据缓冲完了,如何获取这个通知呢? 不错就是使用Thread和Handler结合,在缓冲完成后,使用handler发送一个 空消息 handler.sendEmptyMessage(1); /** * 缓冲加载进程数据 */ private void ini

手机安全卫士学习(2)

今天是安全卫士学习第二天,主要涉及以下内容: 1 安全卫士主页面的布局 其中涉及gridview的使用,包括布局文件的引用,以及自定义控件textview <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width=&qu

(转)Android进程管理详解

Android的原理-不需要太多的剩余内存 不用在意剩余内存的大小.其实很多人都是把使用其他系统的习惯带过来来了.安卓Android大多应用没有退出的设计其实是有道理的,这和系统对进程的调度机制有关系.如果你知道java,就能更清楚这机制了.其实和java的垃圾回收机制类似,系统有一个规则来回收内存.进行内存调度有个阀值,只有低于这个值系统才会按一个列表来关闭用户不需要的东西.当然这个值默认设置得很小,所以你会看到内存老在很少的数值徘徊.但事实上他并不影响速度.相反加快了下次启动应用的速度.这本

手机安全卫士——主界面的开发

activity_home.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent

mschedule 简单linux进程管理(树莓派)

树莓派是神奇的机器,CPU和内存都少的可怜,但体积小功耗低,在上面搞些动搞些西其实也挺有意思,挺好玩的.装的是pidara,基本服务没有精简多少,先cat一下CPU和RAM. [[email protected] ~]$ cat /proc/cpuinfo Processor : ARMv6-compatible processor rev 7 (v6l) BogoMIPS : 464.48 Features : swp half thumb fastmult vfp edsp java tls

Android内存进程管理机制

参考文章: http://www.apkbus.com/android-104940-1-1.htmlhttp://blog.sina.com.cn/s/blog_3e3fcadd0100yjo2.html 一.理论: Android采取了一种有别于Linux的进程管理策略,有别于Linux的在进程活动停止后就结束该进程,Android把这些进程都保留在内存中,直到系统需要更多内存为止.这些保留在内存中的进程通常情况下不会影响整体系统的运行速度,并且当用户再次激活这些进程时,提升了进程的启动速度