我试着写一个简单的任务杀手。我知道我不应该杀掉Android中的任务,但我很想尝试这样的事情。我有以下代码:
List<RunningAppProcessInfo> procInfo = activityManager.getRunningAppProcesses();
for (int i = 0; i < procInfo.size(); i++) {
Log.v("proces " + i,procInfo.get(i).processName + " pid:" + procInfo.get(i).pid + " importance: " + procInfo.get(i).importance + " reason: " + procInfo.get(i).importanceReasonCode);
//First I display all processes into the log
}
for (int i = 0; i < procInfo.size(); i++) {
RunningAppProcessInfo process = procInfo.get(i);
int importance = process.importance;
int pid = process.pid;
String name = process.processName;
if (name.equals("manager.main")) {
//I dont want to kill this application
continue;
}
if (importance == RunningAppProcessInfo.IMPORTANCE_SERVICE) {
//From what I have read about importances at android developers, I asume that I can safely kill everithing except for services, am I right?
Log.v("manager","task " + name + " pid: " + pid + " has importance: " + importance + " WILL NOT KILL");
continue;
}
Log.v("manager","task " + name + " pid: " + pid + " has importance: " + importance + " WILL KILL");
android.os.Process.killProcess(procInfo.get(i).pid);
}
procInfo = activityManager.getRunningAppProcesses();
//I get a new list with running tasks
for (int i = 0; i < procInfo.size(); i++) {
Log.v("proces after killings" + i,procInfo.get(i).processName + " pid:" + procInfo.get(i).pid + " importance: " + procInfo.get(i).importance + " reason: " + procInfo.get(i).importanceReasonCode);
}
我的问题是,当我执行此代码时,我首先获得所有任务的列表,这没关系。比我在日志中看到的几行:
Sending signal. pid: (processId) SIG: 9
我认为这是一个死亡的信号。但是在我的代码结束时,当我显示所有正在运行的进程时,列表与之前相同,没有任务被杀死。任何想法为什么?谢谢!
答案 0 :(得分:2)
要获得killProcess
的最佳结果,请尝试多次调用killProcess
。
for (int i = 0; i < 10; i++)
{
android.os.Process.killProcess(procInfo.get(i).pid);
}
注意:
2.2版 - killBackgroundProcesses:“这与杀死那些进程以回收内存的内核相同;系统将根据需要在将来重新启动这些进程。”
ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
am.killBackgroundProcesses("com.est.testetst");
必需的权限:
android.Manifest.permission.KILL_BACKGROUND_PROCESSES
2.1版 - restartPackage - “不推荐使用此方法。(适用于小于2.2的版本。 现在这只是killBackgroundProcesses(String)的包装器;此处的先前行为不再适用于应用程序,因为它允许它们通过删除其警报,停止其服务等来破坏其他应用程序。“
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
必需的权限:
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
答案 1 :(得分:1)
您不能以这种方式杀死其他任务,因为内核会强制执行权限。试试这个:
ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
activityManager.restartPackage(packageName);
您需要在清单中使用以下权限:
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
编辑:
实际上不推荐使用restartPackage。改为使用killBackgroundProcesses()!
答案 2 :(得分:0)
幸运的是,killProcess()
只能帮助您杀死自己的进程。你可以通过reading the documentation告诉我们。