135.s1-杀死进程

本文介绍了一个Android平台上的进程管理工具的实现细节,包括如何获取进程信息、杀死后台进程、以及用户交互逻辑等。通过ActivityManager获取运行中的进程,并提供界面让用户选择要清理的应用。
摘要由CSDN通过智能技术生成

杀死进程需要依赖ActivityManager,需要权限

<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"></uses-permission>

主布局界面activity_task_manager.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"
    android:orientation="vertical" >
    

    <TextView 
        style="@style/TitleStyle"
        android:text="进程管理"
        />
    <LinearLayout 
        android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
        >
        <TextView 
            android:id="@+id/tv_task_process_count"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="进行中进程1个"
    		android:layout_weight="1"
    		android:layout_marginLeft="5dp"
    		android:textColor="@color/black"
            />
		<TextView 
		    android:id="@+id/tv_task_memory"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="剩余/总内存"
    		android:layout_weight="1"
    		android:layout_marginLeft="5dp"
    		android:textColor="@color/black"
            />        
    </LinearLayout>
    <ListView 
        android:id="@+id/list_view"
        android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:layout_weight="1111"
        ></ListView>
    <LinearLayout 
        android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
        >
        <Button 
            android:id="@+id/btn_select_all"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:layout_weight="1"
    		android:text="全选"
    		android:onClick="btn_select_all"
    		android:background="@drawable/button"
            />
        <Button 
            android:id="@+id/btn_select_oppsite"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:layout_weight="1"
    		android:text="反选"
    		android:onClick="btn_select_oppsite"
    		android:background="@drawable/button"
            />
        <Button 
            android:id="@+id/btn_kill_process"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:layout_weight="1"
    		android:text="清理"
    		android:onClick="btn_kill_process"
    		android:background="@drawable/button"
            />
        <Button 
            android:id="@+id/btn_open_set"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:layout_weight="1"
    		android:text="设置"
    		android:onClick="btn_open_set"
    		android:background="@drawable/button"
            />
        
    </LinearLayout>
</LinearLayout>

ListView布局item_task_manager.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"
    android:orientation="horizontal" >
    

    <ImageView 
        android:id="@+id/iv_icon"
        android:layout_width="50dp"
    	android:layout_height="50dp"
    	android:background="@drawable/ic_launcher"
        />
    <LinearLayout 
        android:layout_width="wrap_content"
    	android:layout_height="wrap_content"
    	android:layout_marginLeft="5dp"
    	android:orientation="vertical"
        >
        <TextView 
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:textSize="20sp"
    		android:textColor="@color/black"
    		android:singleLine="true"
    		android:text="手机卫视"
            />
        <TextView 
            android:id="@+id/tv_app_memory_size"
            android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:textSize="16sp"
    		android:layout_marginTop="2dp"
    		android:singleLine="true"
    		android:text="手机内存占用:1M"
            />     
    </LinearLayout>
    <RelativeLayout 
        android:layout_width="wrap_content"
   		android:layout_height="wrap_content"
        >
	   	<CheckBox
	   	    android:id="@+id/tv_app_status" 
	        android:layout_width="wrap_content"
	   		android:layout_height="wrap_content"
	   		android:textSize="16sp"
	   		android:layout_marginTop="10dp"
	   		android:layout_marginRight="10dp"
	   		android:singleLine="true"
	   		android:layout_alignParentRight="true"
	   		android:focusable="false"
	   		android:clickable="false"
	            />	        
    </RelativeLayout>

</LinearLayout>

进程设置界面item_task_manager_setting.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"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="60dip"
        android:background="#8866ff00"
        android:gravity="center"
        android:text="进程管理设置"
        android:textSize="24sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <CheckBox
            android:id="@+id/cb_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="显示系统进程" />
    </LinearLayout>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <CheckBox
            android:id="@+id/cb_status_kill_process"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="定时清理进程" />
    </LinearLayout>

</LinearLayout>

主界面逻辑文件TaskManageActivityr.java

package com.ldw.safe.Activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ldw.safe.R;
import com.ldw.safe.bean.TaskInfo;
import com.ldw.safe.engine.TaskInfoParser;
import com.ldw.safe.utils.SharedPreferencesUtils;
import com.ldw.safe.utils.SystemInfoUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

/*
 * 进程管理
 */
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 availMem;
	private long totalMem;
	private List<TaskInfo> taskInfos;
	private List<TaskInfo> userTaskInfos;
	private List<TaskInfo> systemAppInfos;
	private TaskManagerAdapter adapter;
	private int processCount;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        //初始化界面
        initUi();
        initData();
	}
	
	@Override
	protected void onResume() {
		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);// 多了一个textview的标签 ,
															// 位置需要-1
			} else {
				// 系统程序
				int location = position - 1 - userTaskInfos.size() - 1;
				taskInfo = systemAppInfos.get(location);
			}
			return taskInfo;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			//初始化动作,区分系统进程和第三方进程
			if (position == 0) {
				// 第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;
			
			view = View.inflate(TaskManagerActivity.this, R.layout.item_task_manager, null);
			
			holder = new ViewHolder();
			holder.iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
			holder.tv_name = (TextView) view.findViewById(R.id.tv_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);// 多了一个textview的标签 ,
															// 位置需要-1
			} else {
				// 系统程序
				int location = position - 1 - userTaskInfos.size() - 1;
				taskInfo = systemAppInfos.get(location);
			}
			
			//设置图标
			holder.iv_icon.setImageDrawable(taskInfo.getIcon());
			//设置应用的名字
			holder.tv_name.setText(taskInfo.getAppName());
			//设置应用的大小
			holder.tv_app_memory_size.setText("内存占用:"
					+ Formatter.formatFileSize(TaskManagerActivity.this,
							taskInfo.getMemorySize()));
			//判断checkBox是否被选中
			if (taskInfo.isChecked()) {
				holder.tv_app_status.setChecked(true);
			} else {
				holder.tv_app_status.setChecked(false);
			}
			
			
			return view;
		}
		
	}
	
	static class ViewHolder{
		ImageView iv_icon;
		TextView tv_name;
		TextView tv_app_memory_size;
		CheckBox tv_app_status;
	}
	
	/*
	private Handler handler = new Handler(){

		public void handlerMessage(android.os.Message msg){
			adapter = new TaskManagerAdapter();
			list_view.setAdapter(adapter);
		};
	};
	*/

	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);
					}
				}
				//不用发消息的方法显示
				//handler.sendEmptyMessage(0);
				
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						adapter = new TaskManagerAdapter();
						list_view.setAdapter(adapter);
					}
				});
				
			};
		}.start();
		
	}

	/*
	 * PackageManager包管理器
	 * ActivityManager活动管理器(任务管理器)
	 */
	//初始化界面
	private void initUi() {
		setContentView(R.layout.activity_task_manager);
		ViewUtils.inject(this);
		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) {
				//获取到条目中的对象和 getItem一起使用
				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;
					}
					
					//判断当前item是否被选中
					if(taskInfo.isChecked()){
						taskInfo.setChecked(false);
						holder.tv_app_status.setChecked(false);
					} else {
						taskInfo.setChecked(true);
						holder.tv_app_status.setChecked(true);
					}
				}
			}
			
		});
		
		/*代码整合到工具类中
		MemoryInfo memoryInfo = new MemoryInfo();
		//获取内存信息
		activityManager.getMemoryInfo(memoryInfo);
		
		availMem = memoryInfo.availMem;
		//这个代码不支持低版本手机
		totalMem = memoryInfo.totalMem;

		//手机总内存的文件保存在/proc/meminfo文件中的第一条,读取这个可以获取到总内存
		//这个形式表示MemTotal: 344740 kB
		
		// /proc/meminfo 配置文件的路径
			try {
				//创建一个输入流,配置文件的路径
				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);
					}
				}
				
				totalMem = Long.parseLong(sb.toString()) * 1024;
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		tv_task_memory.setText("剩余/总内存:" + 
		Formatter.formatFileSize(TaskManagerActivity.this, availMem) + "/" +
				Formatter.formatFileSize(TaskManagerActivity.this, totalMem));
		*/
		
	}
	
	/*
	 * 全选
	 */
	public void btn_select_all(View v){
		//用户应用勾选
		for(TaskInfo taskInfo:userTaskInfos){
			//不能勾选自己app
			if (taskInfo.getPackageName().equals(getPackageName())) {
				continue;
			}
			taskInfo.setChecked(true);
		}
		
		for (TaskInfo taskInfo : systemAppInfos) {
			taskInfo.setChecked(true);
		}
		// 一定要注意。一旦数据发生改变一定要刷新
		adapter.notifyDataSetChanged();
	}
	
	/*
	 * 反选
	 */
	public void btn_select_oppsite(View v){
		for(TaskInfo taskInfo:userTaskInfos){
			if (taskInfo.getPackageName().equals(getPackageName())) {
				continue;
			}
			taskInfo.setChecked(!taskInfo.isChecked());
		}
		
		for (TaskInfo taskInfo : systemAppInfos) {
			taskInfo.setChecked(!taskInfo.isChecked());
		}
		// 一定要注意。一旦数据发生改变一定要刷新
		adapter.notifyDataSetChanged();
	}
	
	/*
	 * 杀死进程
	 */
	public void btn_kill_process(View v){
		// 想杀死进程。首先必须得到进程管理器
		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();
			}
		}
		
		//注意: 当集合在迭代的时候。不能修改集合的大小
		for (TaskInfo taskInfo : killLists) {
			// 判断是否是用户app
			if (taskInfo.isUserApp()) {
				userTaskInfos.remove(taskInfo);
				// 杀死进程 参数表示包名
				activityManager.killBackgroundProcesses(taskInfo
						.getPackageName());
			} else {
				systemAppInfos.remove(taskInfo);
				// 杀死进程 参数表示包名
				activityManager.killBackgroundProcesses(taskInfo
						.getPackageName());
			}
		}
		
		Toast.makeText(
				TaskManagerActivity.this,
				"共清理"
						+ totalCount
						+ "个进程,释放"
						+ Formatter.formatFileSize(TaskManagerActivity.this,
								killMem) + "内存", Toast.LENGTH_SHORT).show();
		
		//processCount 表示总共有多少个进程
		//totalCount 当前清理了多少个进程
		processCount -= totalCount; 
		tv_task_process_count.setText("进程:"+ processCount +"个");
		
		tv_task_memory.setText("剩余/总内存:" + 
				Formatter.formatFileSize(TaskManagerActivity.this, availMem) + "/" +
						Formatter.formatFileSize(TaskManagerActivity.this, totalMem));
		// 刷新界面
		adapter.notifyDataSetChanged();
		
	}
	
	public void btn_open_set(View v){
		Intent intent = new Intent(this,TaskManagerSettingActivity.class);
		startActivity(intent);
	}
}

设置界面逻辑文件ActivityTaskManagerSetting.java

package com.ldw.safe.Activity;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.ldw.safe.R;
import com.ldw.safe.utils.SharedPreferencesUtils;

/*
 * 进程设置
 */
public class TaskManagerSettingActivity extends Activity {

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initUI();
		
	}
	
	private void initUI() {
		setContentView(R.layout.activity_task_manager_setting);
		CheckBox cb_status = (CheckBox) findViewById(R.id.cb_status);
		
		//设置是否选中
		cb_status.setChecked(SharedPreferencesUtils.getBoolean(TaskManagerSettingActivity.this, "is_show_system", false));
		
		cb_status.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				SharedPreferencesUtils.saveBoolean(TaskManagerSettingActivity.this, "is_show_system", isChecked);
			}
		});	
	}

}

工具类SystemInfoUtils.java获取可以用的内存和总内存的大小以及内存个数的方法

package com.ldw.safe.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;

public class SystemInfoUtils {

	/*
	 * 检测服务是否运行
	 */
	public static boolean isServiceRunning(Context ctx, String serviceName){
		
		//利用context获取到系统的服务
		ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
		//获取到正在运行的服务,100是返回服务的最大值
		List<RunningServiceInfo> runningService = am.getRunningServices(100);
		//遍历服务
		for(RunningServiceInfo runningServiceInfo:runningService){
			//获取服务的名字
			String className = runningServiceInfo.service.getClassName();
			//System.out.println(className);
			//判断系统里面有没有这个服务,有这个服务就返回true
			if(className.equals(serviceName)){
				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) {
		// 获取到总内存
		/*
		 * 这个地方不能直接跑到低版本的手机上面 MemTotal: 344740 kB "/proc/meminfo"
		 */
		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;

	}
}

 

获取到所有的进程的信息TaskInfoParser.java

 

 

package com.ldw.safe.engine;

import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
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.ldw.safe.R;
import com.ldw.safe.bean.TaskInfo;

/*
 * 进程信息的逻辑文件
 */
public class TaskInfoParser {
	
	public static List<TaskInfo> getTaskInfos(Context context) {
		
		//PackageManager包管理器
		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){
			//创建一个进程的bean
			TaskInfo taskInfo = new TaskInfo();
			//获取到进程的名字
			String processName = runningAppProcessInfo.processName;
			
			taskInfo.setPackageName(processName);
			
			try {
				//获取到进程的包的信息
				PackageInfo packageInfo = packageManager.getPackageInfo(processName, 0);
				//获取到进程的PIDS,只有一个数据
				MemoryInfo[] memoryInfo = activityManager
						.getProcessMemoryInfo(new int[]{runningAppProcessInfo.pid});
				// Dirty弄脏
				// 获取到总共弄脏多少内存(当前应用程序占用多少内存)
				int totalPrivateDirty = memoryInfo[0].getTotalPrivateDirty() * 1024;
				
				
				// /获取到图片
				Drawable icon = packageInfo.applicationInfo
						.loadIcon(packageManager);
				// 获取到应用的名字
				String appName = packageInfo.applicationInfo.loadLabel(
						packageManager).toString();
				
				taskInfo.setAppName(appName);
				taskInfo.setMemorySize(totalPrivateDirty);
				taskInfo.setIcon(icon);
				
				
				System.out.println("-------------------");
				System.out.println("processName="+processName);
				System.out.println("appName="+appName);
				
				//获取到当前应用程序的标记
				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();
				//没有图标的额时候设置默认的图标,将app的名字设置成进程名字
				taskInfo.setAppName(processName);
				taskInfo.setIcon(context.getResources().getDrawable(
						R.drawable.ic_launcher));
			}
			TaskInfos.add(taskInfo);
			
		}
		
		return TaskInfos;
	}

}

进程信息的javabean.java

package com.ldw.safe.bean;

import android.graphics.drawable.Drawable;

/*
 * 进程的bean文件
 */
public class TaskInfo {

	private Drawable icon;
	private String packageName;
	private String appName;
	private long memorySize;
	//是否是用户进程
	private boolean userApp;
	 //判断当前的item的条目是否被勾选上
	private boolean 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;
	}
	public boolean isChecked() {
		return checked;
	}
	public void setChecked(boolean checked) {
		this.checked = checked;
	}
	@Override
	public String toString() {
		return "TaskInfo [icon=" + icon + ", packageName=" + packageName
				+ ", appName=" + appName + ", memorySize=" + memorySize
				+ ", userApp=" + userApp + ", checked=" + checked + "]";
	}
	
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值