Android获取正在运行的程序并kill掉它

来源:互联网 发布:什么是数据架构 编辑:程序博客网 时间:2024/05/17 00:58

获取正在运行的程序并把它加入到一个listview的adapter类面,方法如下:

// 正在运行的public List<Programe> getRunningProcess() {pi = new PackagesInfo(this);am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);// 获取正在运行的应用run = am.getRunningAppProcesses();// 获取包管理器,在这里主要通过包名获取程序的图标和程序名pm = this.getPackageManager();List<Programe> list = new ArrayList<Programe>();for (RunningAppProcessInfo ra : run) {// 这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。if (ra.processName.equals("system")|| ra.processName.equals("com.android.phone")) {continue;}if (pi.getInfo(ra.processName) == null) {continue;}int[] myMempid = new int[] { ra.pid };Programe pr = new Programe();String xx = "" + ra.processName;Log.d("zphlog", "ra.processName=" + xx);pr.setIcon(pi.getInfo(ra.processName).loadIcon(pm));pr.setName(pi.getInfo(ra.processName).loadLabel(pm).toString());System.out.println(pi.getInfo(ra.processName).loadLabel(pm).toString());// PIDpr.setPID("PID:" + ra.pid);// memoryDebug.MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(myMempid);double memSize = memoryInfo[0].dalvikPrivateDirty / 1024.0;int temp = (int) (memSize * 100);memSize = temp / 100.0;pr.setMemory("Memory:" + memSize);list.add(pr);}return list;}

下面是获取正在运行程序,手机剩余可运行内存的方法:

// 更新可用内存信息public void upDateMemAndPakInfo() {// 获得MemoryInfo对象ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();// 获得系统可用内存,保存在MemoryInfo对象上am.getMemoryInfo(memoryInfo);long memSize = memoryInfo.availMem;// 字符类型转换String restMemSize = Formatter.formatFileSize(getBaseContext(), memSize);mRestMemory.setText("剩余空间还有:" + restMemSize);// mPakcgeNums.setText(run.size());mPakcgeNums.setText("正在运行的有:" + run.size() + "个");}

看一下效果图


下面是详细代码:

ActivityMain.java

public class ActivityMain extends Activity {private static final int MSG_REFRESH = 555;private static final int MSG_KILL = 444;private ListView mListView;private Button mKillBtn;private Button mRefreshBtn;private TextView mPakcgeNums;private TextView mRestMemory;private PackagesInfo pi;private ActivityManager am;private List<RunningAppProcessInfo> run;private PackageManager pm;private long mExitTime;private static final int EXIT = 0x113;private static final int ABOUT = 0x114;private static final int INFO = 0x115;private static final int SHARE = 0x116;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);this.requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.activity_main);mListView = (ListView) findViewById(R.id.list);mKillBtn = (Button) findViewById(R.id.kill_all);mRefreshBtn = (Button) findViewById(R.id.refresh_run);mPakcgeNums = (TextView) findViewById(R.id.packagenums);mRestMemory = (TextView) findViewById(R.id.restmemory);List<Programe> list = getRunningProcess();ListAdapter adapter = new ListAdapter(list, this);mListView.setAdapter(adapter);upDateMemAndPakInfo();// 显示Memory信息// getListView().setAdapter(adapter);mKillBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubhandler.sendEmptyMessage(MSG_KILL);}});mRefreshBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew Thread() {public void run() {handler.sendEmptyMessage(MSG_REFRESH);}}.start();}});}// 正在运行的public List<Programe> getRunningProcess() {pi = new PackagesInfo(this);am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);// 获取正在运行的应用run = am.getRunningAppProcesses();// 获取包管理器,在这里主要通过包名获取程序的图标和程序名pm = this.getPackageManager();List<Programe> list = new ArrayList<Programe>();for (RunningAppProcessInfo ra : run) {// 这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。if (ra.processName.equals("system")|| ra.processName.equals("com.android.phone")) {continue;}if (pi.getInfo(ra.processName) == null) {continue;}int[] myMempid = new int[] { ra.pid };Programe pr = new Programe();String xx = "" + ra.processName;Log.d("zphlog", "ra.processName=" + xx);pr.setIcon(pi.getInfo(ra.processName).loadIcon(pm));pr.setName(pi.getInfo(ra.processName).loadLabel(pm).toString());System.out.println(pi.getInfo(ra.processName).loadLabel(pm).toString());// PIDpr.setPID("PID:" + ra.pid);// memoryDebug.MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(myMempid);double memSize = memoryInfo[0].dalvikPrivateDirty / 1024.0;int temp = (int) (memSize * 100);memSize = temp / 100.0;pr.setMemory("Memory:" + memSize);list.add(pr);}return list;}Handler handler = new Handler() {public void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case MSG_REFRESH:List<Programe> list = getRunningProcess();ListAdapter adapter = new ListAdapter(list, ActivityMain.this);mListView.setAdapter(adapter);upDateMemAndPakInfo();Toast.makeText(ActivityMain.this, "刷新成功", Toast.LENGTH_SHORT).show();break;case MSG_KILL:for (RunningAppProcessInfo ra : run) {// 这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。if (ra.processName.equals("system")|| ra.processName.equals("com.android.phone")) {continue;}if (pi.getInfo(ra.processName) == null) {continue;}am.killBackgroundProcesses(ra.processName); //Log.d("zphlog","pid="+ra.pid);}Toast.makeText(ActivityMain.this, "kill 成功", Toast.LENGTH_SHORT).show();break;}}};// 更新可用内存信息public void upDateMemAndPakInfo() {// 获得MemoryInfo对象ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();// 获得系统可用内存,保存在MemoryInfo对象上am.getMemoryInfo(memoryInfo);long memSize = memoryInfo.availMem;// 字符类型转换String restMemSize = Formatter.formatFileSize(getBaseContext(), memSize);mRestMemory.setText("剩余空间还有:" + restMemSize);// mPakcgeNums.setText(run.size());mPakcgeNums.setText("正在运行的有:" + run.size() + "个");}// 点击手机返回键返回到上一个界面public boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {if ((System.currentTimeMillis() - mExitTime) > 2000) {Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();mExitTime = System.currentTimeMillis();} else {finish();}return true;}return super.onKeyDown(keyCode, event);} @Overridepublic boolean onCreateOptionsMenu(Menu menu) {menu.add(0, ABOUT, 0, "关于应用");menu.add(0, INFO, 0, "系统信息");menu.add(0, SHARE, 0, "分享应用");menu.add(0, EXIT, 0, "退出应用");return super.onCreateOptionsMenu(menu);}@Overridepublic boolean onOptionsItemSelected(MenuItem mi){switch (mi.getItemId()){case ABOUT:about_info();break;case INFO:system_info();break;case SHARE:share();break;case EXIT:finish();break;}return true;}public void about_info(){Intent intent = new Intent(this, AboutTaskKiller.class);startActivity(intent);}public void system_info(){Intent intent = new Intent(this, SystemInfo.class);startActivity(intent);}public void share(){Intent intent=new Intent(Intent.ACTION_SEND);  intent.setType("text/plain");  //纯文本intent.putExtra(Intent.EXTRA_SUBJECT, "分享");  intent.putExtra(Intent.EXTRA_TEXT, "我发现了一个好用的TaskKiller");  startActivity(intent);  }}
ListAdapter.java

public class ListAdapter extends BaseAdapter {List<Programe> list = new ArrayList<Programe>();LayoutInflater la;Context context;public ListAdapter(List<Programe> list, Context context) {this.list = list;this.context = context;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn list.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder;if (convertView == null) {la = LayoutInflater.from(context);convertView = la.inflate(R.layout.list_item, null);holder = new ViewHolder();holder.imgage = (ImageView) convertView.findViewById(R.id.image);holder.text = (TextView) convertView.findViewById(R.id.text);holder.PID = (TextView) convertView.findViewById(R.id.pid);holder.memory = (TextView) convertView.findViewById(R.id.memory);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}final Programe pr = (Programe) list.get(position);// 设置图标holder.imgage.setImageDrawable(pr.getIcon());// 设置程序名holder.text.setText(pr.getName());// 设置PIDholder.PID.setText(pr.getPID());// 设置memoryholder.memory.setText(pr.getMemory());return convertView;}}class ViewHolder {TextView text;ImageView imgage;TextView memory;TextView PID;}

Programe.java

public class Programe {// 图标private Drawable icon;// 程序名private String name;private String pID;private String memory;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 void setPID(String id){this.pID = id;}public  String getPID(){return pID;}public void setMemory(String m){this.memory = m;}public String getMemory(){return memory;}}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".ActivityMain" >    <LinearLayout        android:id="@+id/layout_info"        android:layout_width="fill_parent"        android:layout_height="35dip"        android:background="#B0C4DE"        android:orientation="horizontal" >        <TextView            android:id="@+id/packagenums"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_margin="8dip"            android:layout_weight="1"            android:text="packagenums"            android:textColor="#000000"            android:textSize="14sp" />        <TextView            android:id="@+id/restmemory"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_margin="8dip"            android:layout_weight="1"            android:text="packagenums"            android:textColor="#000000"            android:textSize="14sp" />    </LinearLayout>    <LinearLayout        android:id="@+id/layout_buttons"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_below="@id/layout_info"        android:background="#808080"        android:orientation="horizontal" >        <Button            android:id="@+id/kill_all"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_margin="10dip"            android:layout_weight="1"            android:text="kill All" />        <Button            android:id="@+id/refresh_run"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_margin="10dip"            android:layout_weight="1"            android:text="refresh" />    </LinearLayout>    <ListView        android:id="@+id/list"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_below="@id/layout_buttons"        android:background="#808080"        android:paddingBottom="@dimen/activity_vertical_margin"        android:paddingLeft="@dimen/activity_horizontal_margin"        android:paddingRight="@dimen/activity_horizontal_margin" /></RelativeLayout>

list_item.xml

<?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="horizontal" >    <ImageView        android:id="@+id/image"        android:layout_width="50dip"        android:layout_height="50dip"        android:layout_marginLeft="10dip" />    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginLeft="20dip"        android:layout_toRightOf="@id/image"        android:orientation="vertical" >        <TextView            android:id="@+id/text"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="package" />        <TextView            android:id="@+id/pid"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="pid" />        <TextView            android:id="@+id/memory"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="memory" />    </LinearLayout></RelativeLayout>

以上都是主要实现的代码,因为篇幅的原因,我就不再这里继续粘贴代码了,大概总结一下我的思路。

首先就是最开始我谈到的获取正在运行的程序信息。

可以通过下面的方式得到

// 正在运行的
public List<Programe> getRunningProcess() {
pi = new PackagesInfo(this);


am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
// 获取正在运行的应用
run = am.getRunningAppProcesses();
// 获取包管理器,在这里主要通过包名获取程序的图标和程序名
pm = this.getPackageManager();
List<Programe> list = new ArrayList<Programe>();


for (RunningAppProcessInfo ra : run) {
// 这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。
if (ra.processName.equals("system")
|| ra.processName.equals("com.android.phone")) {
continue;
}
if (pi.getInfo(ra.processName) == null) {
continue;
}
int[] myMempid = new int[] { ra.pid };
Programe pr = new Programe();
String xx = "" + ra.processName;
Log.d("zphlog", "ra.processName=" + xx);
pr.setIcon(pi.getInfo(ra.processName).loadIcon(pm));
pr.setName(pi.getInfo(ra.processName).loadLabel(pm).toString());


System.out.println(pi.getInfo(ra.processName).loadLabel(pm)
.toString());
// PID
pr.setPID("PID:" + ra.pid);
// memory
Debug.MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(myMempid);
double memSize = memoryInfo[0].dalvikPrivateDirty / 1024.0;
int temp = (int) (memSize * 100);
memSize = temp / 100.0;
pr.setMemory("Memory:" + memSize);


list.add(pr);
}
return list;
}

然后就是把得到的信息保存在listview的一个Adapter里面。

接着就是kill掉他们,我在网上看到有三种方式可以kill程序,我这里用的方法是

for (RunningAppProcessInfo ra : run) {// 这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。if (ra.processName.equals("system")|| ra.processName.equals("com.android.phone")) {continue;}if (pi.getInfo(ra.processName) == null) {continue;}am.killBackgroundProcesses(ra.processName); //Log.d("zphlog","pid="+ra.pid);}
当然是在for循环里面进行的,后面就是加了一些其他的东西,比如启动的时候要扫描正在运行的程序需要一段时间,我们可以给程序启动的时候让它读取一个图片,停留两秒或者三秒来争取加载运行程序列表信息的时间。

我用的是一个Activity 命名StartUI.java

public class StartUI extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);setContentView(R.layout.welcome_activity);new Handler().postDelayed(new Runnable() {@Overridepublic void run() {Intent intent = new Intent(StartUI.this, ActivityMain.class);startActivity(intent);StartUI.this.finish();}}, 2500);}}
它的布局文件其实就是个简单的ImageView。

下面附上我写的一个简单Demo,源码下载地址

<a target=_blank href="http://download.csdn.net/detail/u010443618/9286009">http://download.csdn.net/detail/u010443618/7829959</a>
做好的Apk下载地址

http://download.csdn.net/detail/u010443618/7829977

如有疑问或者建议我乐意和大家交流

github:https://github.com/PishumAndroid/GetRunsPak


1 0