当前位置: 首页 > >

Android完全杀死进程

发布时间:

查了下官网,android.os.Process.killProcess(appProcessInfo.pid);只能杀死自己所创建的进程,其它进程是杀不掉的,要用到另外一个方法activityManager.killBackgroundProcesses(processName);,同是权限也要加上


以下是我的测试代码
public class ListViewActivity extends Activity {
?


?private Button button;


?@Override
?public void onCreate(Bundle savedInstanceState) {
??super.onCreate(savedInstanceState);
??setContentView(R.layout.main);
??button = (Button) findViewById(R.id.button);
??
??button.setOnClickListener(new OnClickListener() {
???@Override
???public void onClick(View v) {
????killAll(getApplicationContext());
???}
??});
?}


?public static void killAll(Context context) {


   //获取一个ActivityManager?对象
??????? ActivityManager activityManager = (ActivityManager) context
??????????????????????? .getSystemService(Context.ACTIVITY_SERVICE);


   //获取系统中所有正在运行的进程


?????? List appProcessInfos = activityManager
??????????????????????? .getRunningAppProcesses();


  //获取当前activity所在的进程
????? String currentProcess=context.getApplicationInfo().processName;


  //对系统中所有正在运行的进程进行迭代,如果进程名不是当前进程,则Kill掉
?????? for (RunningAppProcessInfo appProcessInfo : appProcessInfos) {
??? ???   String processName=appProcessInfo.processName;
??? ???   if (!processName.equals(currentProcess)) {
????      System.out.println("ApplicationInfo-->"+processName);
????      activityManager.killBackgroundProcesses(processName);
????      System.out.println("Killed -->PID:"+appProcessInfo.pid+"--ProcessName:"+processName);
???    }
???????   }
  }


}


注意进程的过滤,以免把主要的进程也结束了



友情链接: