android适配器simpleadapter和baseadapter
设计网络程序或者数据处理显示程序的时候,常常会使用simpleadapter和baseadapter来实现。adapter是适配器模式,是数据和界面之间的桥梁。baseadapter是一个抽象的类,要使用必需为其定义子类并实现相关方法。simpleadapter派生于baseadapter,已经实现了相关的方法,所以可以直接使用。二者在使用效果上没有太大的区别,两者可以设计出几乎一模一样的界面。但在使用方法上,baseadapter需要创建一个派生于该类的子类,并实现父类的一些方法,他可以根据我们界面和数据的需要自由的定制。simpleadapter可以直接使用,但该适配器使用的数据结构是HashMap,这意味着,如果需要操作的数据对象结构过于复杂时,比如成员很多,成员内容不是基本类型等情况时,需要写相关的转化代码,这会便利程序的效率和可维护性变差。有时,我们会面临使用哪种适配器的问题。如果数据结构很简单,操作的数据对象成员很少,没有非基本类型的数据成员,只是做为简单的展示,那么simpleadapter是很好的选择,简捷高效快速。如果成员很多,成员中包含复杂的对象,如Button,darwable等,使用baseadapter会让代码变得简捷效率。
1个简单的simpleadapter对象,由于数据成员中含有drawable对象,需要重载setViewBinder特别处理
packagecom.example.task;
importjava.io.BufferedReader;
importjava.io.FileReader;
importjava.io.IOException;
importjava.lang.reflect.InvocationTargetException;
importjava.lang.reflect.Method;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importandroid.app.Activity;
importandroid.app.ActivityManager;
importandroid.app.ActivityManager.MemoryInfo;
importandroid.app.ActivityManager.RunningAppProcessInfo;
importandroid.content.Context;
importandroid.content.pm.ApplicationInfo;
importandroid.content.pm.PackageManager;
importandroid.graphics.drawable.Drawable;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.Menu;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemClickListener;
importandroid.widget.Button;
importandroid.widget.ImageView;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;
importandroid.widget.SimpleAdapter.ViewBinder;
importandroid.widget.TextView;
publicclass Task2 extends Activity {
TextViewtv1;
TextViewtv2;
ListViewlv;
SimpleAdapteradapter;
ArrayList<HashMap<String,Object>> items = new ArrayList<HashMap<String,Object>>();
PackageManagerpm;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1= (TextView) findViewById(R.id.textView1);
tv1.setText(getString(R.string.freememory)
+String.valueOf(getAvailMemory(this))
+getString(R.string.totalmemory)
+String.valueOf(getTotalMemory(this)));
tv2= (TextView) findViewById(R.id.textView2);
Buttonrm = (Button) findViewById(R.id.button1);
rm.setOnClickListener(newOnClickListener() {
@Override
publicvoid onClick(View v) {
//TODO Auto-generated method stub
killtask2(Task2.this);
Stringtm = Task2.this.getString(R.string.totalmemory);
Stringfm = Task2.this.getString(R.string.freememory);
tv1.setText(fm+ String.valueOf(getAvailMemory(Task2.this))
+tm + String.valueOf(getTotalMemory(Task2.this)));
//adapter.notify();
lv.setAdapter(CreateSimpleAdapterList());
adapter.notifyDataSetInvalidated();
}
});
Buttonsrm = (Button) findViewById(R.id.button2);
srm.setOnClickListener(newOnClickListener() {
@Override
publicvoid onClick(View v) {
//TODO Auto-generated method stub
killtask(Task2.this);
Stringtm = Task2.this.getString(R.string.totalmemory);
Stringfm = Task2.this.getString(R.string.freememory);
tv1.setText(fm+ String.valueOf(getAvailMemory(Task2.this))
+tm + String.valueOf(getTotalMemory(Task2.this)));
}
});
lv= (ListView) findViewById(R.id.listView1);
lv.setAdapter(CreateSimpleAdapterList());
lv.setOnItemClickListener(newOnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView<?> parent, View view,
intposition, long id) {
//TODO Auto-generated method stub
StringpackageName = (String) items.get(position).get(
"packageName");
Stringappname = (String) items.get(position).get("appName");
//取到点击的包名
ActivityManageram = (ActivityManager) Task2.this
.getSystemService(ACTIVITY_SERVICE);
am.killBackgroundProcesses(packageName);
lv.setAdapter(CreateSimpleAdapterList());
adapter.notifyDataSetInvalidated();
}
});
}
publicSimpleAdapter CreateSimpleAdapterList() {
CreateRunList();
adapter= new SimpleAdapter(this, items, R.layout.task_list,
newString[] { "icon", "appName", "ProcessName","packageName",
"Pid","User" }, new int[] { R.id.image, R.id.name,
R.id.pkg,R.id.process, R.id.id, R.id.User });
adapter.setViewBinder(newViewBinder() {
publicboolean setViewValue(View view, Object data,
StringtextRepresentation) {
if(view instanceof ImageView && data instanceof Drawable) {
ImageViewiv = (ImageView) view;
iv.setImageDrawable((Drawable)data);
returntrue;
}else
returnfalse;
}
});
returnadapter;
}
publicvoid CreateRunList() {
List<RunningAppInfo>mlistAppInfo = getRunningProcess();
for(RunningAppInfo ra : mlistAppInfo) {
HashMap<String,Object> map = new HashMap<String, Object>();
//取到点击的包名
//图标
map.put("icon",ra.getAppIcon());
//应用名
map.put("appName","名字:"+ ra.getAppLabel());
//包名
map.put("packageName","包名:"+ ra.getPkgName());
//进程名
map.put("ProcessName","进程名:"+ ra.getProcessName());
//进程ID
map.put("Pid","ID:"+ String.valueOf(ra.getPid()));
map.put("User","权限:"+ ra.getUser());
items.add(map);
//循环读取存到HashMap,再增加到ArrayList.一个HashMap就是一项
}
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
privatestatic long getAvailMemory(Context context) {
//获取android当前可用内存大小
ActivityManageram = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfomi = new MemoryInfo();
am.getMemoryInfo(mi);
//mi.availMem; 当前系统的可用内存
//return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
returnmi.availMem / (1024 * 1024);
}
privatestatic long getTotalMemory(Context context) {
Stringstr1 = "/proc/meminfo";// 系统内存信息文件
Stringstr2;
String[]arrayOfString;
longinitial_memory = 0;
try{
FileReaderlocalFileReader = new FileReader(str1);
BufferedReaderlocalBufferedReader = new BufferedReader(
localFileReader,8192);
str2= localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小
arrayOfString= str2.split("\\s+");
for(String num : arrayOfString) {
Log.i(str2,num + "\t");
}
initial_memory= Integer.valueOf(arrayOfString[1]).intValue() * 1024;//获得系统总内存,单位是KB,乘以1024转换为Byte
localBufferedReader.close();
}catch (IOException e) {
}
//return Formatter.formatFileSize(context, initial_memory);//
//Byte转换为KB或者MB,内存大小规格化
returninitial_memory / (1024 * 1024);
}
privatestatic void killtask(Context context) {
ActivityManageractivityManger = (ActivityManager) context
.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo>list = activityManger
.getRunningAppProcesses();
if(list != null)
for(int i = 0; i < list.size(); i++) {
ActivityManager.RunningAppProcessInfoapinfo = list.get(i);
System.out.println("pid" + apinfo.pid);
System.out.println("processName" + apinfo.processName);
System.out.println("importance" + apinfo.importance);
String[]pkgList = apinfo.pkgList;
//if (apinfo.importance >
//ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
//Process.killProcess(apinfo.pid);
for(int j = 0; j < pkgList.length; j++) {
//2.2以上是过时的,请用killBackgroundProcesses代替
if(android.os.Build.VERSION.SDK_INT <= 7) {
activityManger.restartPackage(pkgList[j]);
}else if (android.os.Build.VERSION.SDK_INT >= 8) {
activityManger.killBackgroundProcesses(pkgList[j]);
}
}
//}
}
}
//在android2.2以后,如果服务在ondestroy里加上了start自己,用killbackgroudprocess通常无法结束自己。
privatestatic void killtask2(Context context) {
ActivityManageractivityManger = (ActivityManager) context
.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo>list = activityManger
.getRunningAppProcesses();
if(list != null)
for(int i = 0; i < list.size(); i++) {
ActivityManager.RunningAppProcessInfoapinfo = list.get(i);
System.out.println("pid" + apinfo.pid);
System.out.println("processName" + apinfo.processName);
System.out.println("importance" + apinfo.importance);
String[]pkgList = apinfo.pkgList;
//if (apinfo.importance >
//ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
//Process.killProcess(apinfo.pid);
for(int j = 0; j < pkgList.length; j++) {
//2.2以上是过时的,请用killBackgroundProcesses代替
//activityManger.restartPackage(pkgList[j]);
//activityManger.killBackgroundProcesses(pkgList[j]);
MethodforceStopPackage;
try{
forceStopPackage= activityManger.getClass()
.getDeclaredMethod("forceStopPackage",
String.class);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(activityManger,pkgList[j]);
}catch (NoSuchMethodException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch (IllegalArgumentException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch (IllegalAccessException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch (InvocationTargetException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
//}
}
}
//查询所有正在运行的应用程序信息:包括他们所在的进程id和进程名
//这儿我直接获取了系统里安装的所有应用程序,然后根据报名pkgname过滤获取所有真正运行的应用程序
//正在运行的
publicList<RunningAppInfo> getRunningProcess() {
//PackagesInfo pi = new PackagesInfo(this);
ActivityManageram = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//获取正在运行的应用
List<RunningAppProcessInfo>run = am.getRunningAppProcesses();
//获取包管理器,在这里主要通过包名获取程序的图标和程序名
PackageManagerpm = this.getPackageManager();
List<ApplicationInfo>appList = pm
.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
List<RunningAppInfo>list = new ArrayList<RunningAppInfo>();
tv2.setText(getString(R.string.totalprocess)
+String.valueOf(run.size()));
for(RunningAppProcessInfo ra : run) {
//这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。
/*
* if (ra.processName.equals("system") ||
* ra.processName.equals("com.Android.phone")) { continue; }
*/
for(ApplicationInfo appinfo : appList) {
if((ra.processName).equals(appinfo.processName)) {
/*
* if ((appinfo.flags &
* ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
* continue; } else if ((appinfo.flags &
* ApplicationInfo.FLAG_SYSTEM) != 0) { continue; }
*/
RunningAppInfopr = getAppInfo(appinfo, ra.pid,
ra.processName);
list.add(pr);
}
}
}
returnlist;
}
//构造一个RunningAppInfo对象,并赋值
privateRunningAppInfo getAppInfo(ApplicationInfo app, int pid,
StringprocessName) {
PackageManagerpm = this.getPackageManager();
RunningAppInfoappInfo = new RunningAppInfo();
appInfo.setAppLabel(app.loadLabel(pm).toString());
appInfo.setAppIcon(app.loadIcon(pm));
appInfo.setPkgName(app.packageName);
appInfo.setPid(pid);
appInfo.setProcessName(processName);
if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
appInfo.setUser("System");
}else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
appInfo.setUser("System");
}else {
appInfo.setUser("User");
}
returnappInfo;
}
classRunningAppInfo {
privateString AppLabel = null;
privateDrawable AppIcon = null;
privateString PkgName = null;
privateString ProcessName = null;
privateint Pid = 0;
privateString user = null;
publicString getAppLabel() {
returnAppLabel;
}
publicvoid setAppLabel(String appLabel) {
AppLabel= appLabel.trim();
}
publicDrawable getAppIcon() {
returnAppIcon;
}
publicvoid setAppIcon(Drawable appIcon) {
AppIcon= appIcon;
}
publicString getPkgName() {
returnPkgName;
}
publicvoid setPkgName(String pkgName) {
PkgName= pkgName.trim();
}
publicString getProcessName() {
returnProcessName;
}
publicvoid setProcessName(String processName) {
ProcessName= processName.trim();
}
publicString getUser() {
returnProcessName;
}
publicvoid setUser(String user) {
ProcessName= user;
}
publicint getPid() {
returnPid;
}
publicvoid setPid(int pid) {
Pid= pid;
}
}
}
<RelativeLayoutxmlns: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=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/release"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/strongrelease"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/linearLayout1"
android:layout_centerHorizontal="true">
</ListView>
</LinearLayout>
</RelativeLayout>
<?xmlversion="1.0"encoding="UTF-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/image"
android:layout_width="80dip"
android:layout_height="80dip"
android:layout_marginRight="10dip"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/pkg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/process"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/User"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
2.baseadapter,由于成员中含有图片,按钮对象,同时还要和其他模块交互,串行化为HashMap反而显得复杂,所以使用baseadapter
publicclassListAdapter extendsBaseAdapter {
List<Programe>list = newArrayList<Programe>();
LayoutInflaterla;
Contextcontext;
publicListAdapter(List<Programe> list ,Context context){
this.list= list;
this.context= context;
}
@Override
publicintgetCount() {
//TODOAuto-generated method stub
returnlist.size();
}
@Override
publicObject getItem(intposition) {
//TODOAuto-generated method stub
returnlist.get(position);
}
@Override
publiclonggetItemId(intposition) {
//TODOAuto-generated method stub
returnposition;
}
@Override
publicView getView(intposition, View convertView, ViewGroup parent) {
ViewHolderholder;
if(convertView== null)
{
la= LayoutInflater.from(context);
convertView=la.inflate(R.layout.list_item,null);
holder =newViewHolder();
holder.imgage=(ImageView)convertView.findViewById(R.id.image);
holder.text= (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holder);
}else{
holder =(ViewHolder) convertView.getTag();
}
finalPrograme pr = (Programe)list.get(position);
//设置图标
holder.imgage.setImageDrawable(pr.getIcon());
//设置程序名
holder.text.setText(pr.getName());
returnconvertView;
}
}
classViewHolder{
TextView text;
ImageViewimgage;
}
publicclassTask2 extendsActivity {
TextViewtv1;
TextViewtv2;
ListViewlv;
SimpleAdapteradapter;
ArrayList<HashMap<String,Object>> items= newArrayList<HashMap<String, Object>>();
PackageManagerpm;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1= (TextView) findViewById(R.id.textView1);
tv1.setText(getString(R.string.freememory)
+String.valueOf(getAvailMemory(this))
+getString(R.string.totalmemory)
+String.valueOf(getTotalMemory(this)));
tv2= (TextView) findViewById(R.id.textView2);
Buttonrm = (Button) findViewById(R.id.button1);
rm.setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View v) {
//TODOAuto-generated method stub
killtask2(Task2.this);
Stringtm = Task2.this.getString(R.string.totalmemory);
Stringfm = Task2.this.getString(R.string.freememory);
tv1.setText(fm+ String.valueOf(getAvailMemory(Task2.this))
+tm + String.valueOf(getTotalMemory(Task2.this)));
//adapter.notify();
lv.setAdapter(CreateSimpleAdapterList());
adapter.notifyDataSetInvalidated();
}
});
Buttonsrm = (Button) findViewById(R.id.button2);
srm.setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View v) {
//TODOAuto-generated method stub
killtask(Task2.this);
Stringtm = Task2.this.getString(R.string.totalmemory);
Stringfm = Task2.this.getString(R.string.freememory);
tv1.setText(fm+ String.valueOf(getAvailMemory(Task2.this))
+tm + String.valueOf(getTotalMemory(Task2.this)));
}
});
lv= (ListView) findViewById(R.id.listView1);
lv.setAdapter(CreateSimpleAdapterList());
lv.setOnItemClickListener(newOnItemClickListener() {
@Override
publicvoidonItemClick(AdapterView<?> parent, View view,
intposition, longid) {
//TODOAuto-generated method stub
StringpackageName = (String) items.get(position).get(
"packageName");
Stringappname= (String) items.get(position).get("appName");
//取到点击的包名
ActivityManageram = (ActivityManager) Task2.this
.getSystemService(ACTIVITY_SERVICE);
am.killBackgroundProcesses(packageName);
lv.setAdapter(CreateSimpleAdapterList());
adapter.notifyDataSetInvalidated();
}
});
}
publicSimpleAdapter CreateSimpleAdapterList() {
CreateRunList();
adapter= newSimpleAdapter(this,items,R.layout.task_list,
newString[] { "icon","appName","ProcessName","packageName",
"Pid","User"}, newint[]{ R.id.image,R.id.name,
R.id.pkg,R.id.process,R.id.id,R.id.User});
adapter.setViewBinder(newViewBinder() {
publicbooleansetViewValue(View view, Object data,
StringtextRepresentation) {
if(view instanceofImageView && data instanceofDrawable) {
ImageViewiv = (ImageView) view;
iv.setImageDrawable((Drawable)data);
returntrue;
}else
returnfalse;
}
});
returnadapter;
}
publicvoidCreateRunList() {
List<RunningAppInfo>mlistAppInfo = getRunningProcess();
for(RunningAppInfo ra : mlistAppInfo) {
HashMap<String,Object> map = newHashMap<String, Object>();
//取到点击的包名
//图标
map.put("icon",ra.getAppIcon());
//应用名
map.put("appName","名字:"+ ra.getAppLabel());
//包名
map.put("packageName","包名:"+ ra.getPkgName());
//进程名
map.put("ProcessName","进程名:"+ ra.getProcessName());
//进程ID
map.put("Pid","ID:"+ String.valueOf(ra.getPid()));
map.put("User","权限:"+ ra.getUser());
items.add(map);
//循环读取存到HashMap,再增加到ArrayList.一个HashMap就是一项
}
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
}
privatestaticlonggetAvailMemory(Context context) {
//获取android当前可用内存大小
ActivityManageram = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfomi = newMemoryInfo();
am.getMemoryInfo(mi);
//mi.availMem; 当前系统的可用内存
//return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
returnmi.availMem/ (1024 * 1024);
}
privatestaticlonggetTotalMemory(Context context) {
Stringstr1 = "/proc/meminfo";//系统内存信息文件
Stringstr2;
String[]arrayOfString;
longinitial_memory = 0;
try{
FileReaderlocalFileReader = newFileReader(str1);
BufferedReaderlocalBufferedReader = newBufferedReader(
localFileReader,8192);
str2= localBufferedReader.readLine();//读取meminfo第一行,系统总内存大小
arrayOfString= str2.split("\\s+");
for(String num : arrayOfString) {
Log.i(str2,num + "\t");
}
initial_memory= Integer.valueOf(arrayOfString[1]).intValue()* 1024;// 获得系统总内存,单位是KB,乘以1024转换为Byte
localBufferedReader.close();
}catch(IOException e) {
}
//return Formatter.formatFileSize(context, initial_memory);//
//Byte转换为KB或者MB,内存大小规格化
returninitial_memory / (1024 * 1024);
}
privatestaticvoidkilltask(Context context) {
ActivityManageractivityManger = (ActivityManager) context
.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo>list = activityManger
.getRunningAppProcesses();
if(list != null)
for(inti = 0; i < list.size(); i++) {
ActivityManager.RunningAppProcessInfoapinfo = list.get(i);
System.out.println("pid" + apinfo.pid);
System.out.println("processName" + apinfo.processName);
System.out.println("importance" + apinfo.importance);
String[]pkgList = apinfo.pkgList;
//if (apinfo.importance >
//ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
//Process.killProcess(apinfo.pid);
for(intj = 0; j < pkgList.length;j++) {
//2.2以上是过时的,请用killBackgroundProcesses代替
if(android.os.Build.VERSION.SDK_INT<= 7) {
activityManger.restartPackage(pkgList[j]);
}elseif(android.os.Build.VERSION.SDK_INT>= 8) {
activityManger.killBackgroundProcesses(pkgList[j]);
}
}
//}
}
}
//在android2.2以后,如果服务在ondestroy里加上了start自己,用killbackgroudprocess通常无法结束自己。
privatestaticvoidkilltask2(Context context) {
ActivityManageractivityManger = (ActivityManager) context
.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo>list = activityManger
.getRunningAppProcesses();
if(list != null)
for(inti = 0; i < list.size(); i++) {
ActivityManager.RunningAppProcessInfoapinfo = list.get(i);
System.out.println("pid" + apinfo.pid);
System.out.println("processName" + apinfo.processName);
System.out.println("importance" + apinfo.importance);
String[]pkgList = apinfo.pkgList;
//if (apinfo.importance >
//ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
//Process.killProcess(apinfo.pid);
for(intj = 0; j < pkgList.length;j++) {
//2.2以上是过时的,请用killBackgroundProcesses代替
//activityManger.restartPackage(pkgList[j]);
//activityManger.killBackgroundProcesses(pkgList[j]);
MethodforceStopPackage;
try{
forceStopPackage= activityManger.getClass()
.getDeclaredMethod("forceStopPackage",
String.class);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(activityManger,pkgList[j]);
}catch(NoSuchMethodException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}catch(IllegalArgumentException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {
//TODOAuto-generated catch block
e.printStackTrace();
}
}
//}
}
}
//查询所有正在运行的应用程序信息:包括他们所在的进程id和进程名
//这儿我直接获取了系统里安装的所有应用程序,然后根据报名pkgname过滤获取所有真正运行的应用程序
//正在运行的
publicList<RunningAppInfo> getRunningProcess() {
//PackagesInfo pi = new PackagesInfo(this);
ActivityManageram = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//获取正在运行的应用
List<RunningAppProcessInfo>run = am.getRunningAppProcesses();
//获取包管理器,在这里主要通过包名获取程序的图标和程序名
PackageManagerpm = this.getPackageManager();
List<ApplicationInfo>appList = pm
.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
List<RunningAppInfo>list = newArrayList<RunningAppInfo>();
tv2.setText(getString(R.string.totalprocess)
+String.valueOf(run.size()));
for(RunningAppProcessInfo ra : run) {
//这里主要是过滤系统的应用和电话应用,当然你也可以把它注释掉。
/*
* if (ra.processName.equals("system") ||
* ra.processName.equals("com.Android.phone")) { continue; }
*/
for(ApplicationInfo appinfo : appList) {
if((ra.processName).equals(appinfo.processName)){
/*
* if ((appinfo.flags &
* ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
* continue; } else if ((appinfo.flags &
* ApplicationInfo.FLAG_SYSTEM) != 0) { continue; }
*/
RunningAppInfopr = getAppInfo(appinfo, ra.pid,
ra.processName);
list.add(pr);
}
}
}
returnlist;
}
//构造一个RunningAppInfo对象,并赋值
privateRunningAppInfo getAppInfo(ApplicationInfo app, intpid,
StringprocessName) {
PackageManagerpm = this.getPackageManager();
RunningAppInfoappInfo = newRunningAppInfo();
appInfo.setAppLabel(app.loadLabel(pm).toString());
appInfo.setAppIcon(app.loadIcon(pm));
appInfo.setPkgName(app.packageName);
appInfo.setPid(pid);
appInfo.setProcessName(processName);
if((app.flags& ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)!= 0) {
appInfo.setUser("System");
}elseif((app.flags& ApplicationInfo.FLAG_SYSTEM)!= 0) {
appInfo.setUser("System");
}else{
appInfo.setUser("User");
}
returnappInfo;
}
classRunningAppInfo {
privateString AppLabel= null;
privateDrawable AppIcon= null;
privateString PkgName= null;
privateString ProcessName= null;
privateintPid = 0;
privateString user= null;
publicString getAppLabel() {
returnAppLabel;
}
publicvoidsetAppLabel(String appLabel) {
AppLabel= appLabel.trim();
}
publicDrawable getAppIcon() {
returnAppIcon;
}
publicvoidsetAppIcon(Drawable appIcon) {
AppIcon= appIcon;
}
publicString getPkgName() {
returnPkgName;
}
publicvoidsetPkgName(String pkgName) {
PkgName= pkgName.trim();
}
publicString getProcessName() {
returnProcessName;
}
publicvoidsetProcessName(String processName) {
ProcessName= processName.trim();
}
publicString getUser() {
returnProcessName;
}
publicvoidsetUser(String user) {
ProcessName= user;
}
publicintgetPid() {
returnPid;
}
publicvoidsetPid(intpid) {
Pid= pid;
}
}
}