However the following code works in many cases. To achieve best result, try calling killProcess many times.
For reading the list of running applications and services, please refer to my earlier blog.
Code :public boolean killProcess(Context context, int pid, String packageName) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (pid <= 0) { return false; }
if (pid == android.os.Process.myPid()) {
System.out.println("Killing own process");
android.os.Process.killProcess(pid);
return true;
}
Method method = null;
try {
// Since API_LEVEL 8 : v2.2
method = manager.getClass().getMethod("killBackgroundProcesses", new Class[] { String.class});
} catch (NoSuchMethodException e) {
// less than 2.2
try {
method = manager.getClass().getMethod("restartPackage", new Class[] { String.class });
} catch (NoSuchMethodException ee) {
ee.printStackTrace();
}
}
if (method != null) {
try {
method.invoke(manager, packageName);
System.out.println("kill method " + method.getName()+ " invoked " + packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
android.os.Process.killProcess(pid);
return true;
}
Required Permissions:
android.Manifest.permission.
KILL_BACKGROUND_PROCESSES
NOTE:
- killBackgroundProcesses : " This is the same as the kernel killing those processes to reclaim memory; the system will take care of restarting these processes in the future as needed."
- restartPackage -" This method is deprecated. (works for version less than 2.2.
This is now just a wrapper forkillBackgroundProcesses(String)
; the previous behavior here is no longer available to applications because it allows them to break other applications by removing their alarms, stopping their services, etc."
Nice article, but I can't kill another applications by using the above code in API_LEVEL 8. Is there any other way to close application.
ReplyDelete@Anonymous, use the older method restartPackate() http://developer.android.com/reference/android/app/ActivityManager.html#restartPackage(java.lang.String)
ReplyDeleteIt is also not working
Delete