Android: Killing a running process with processid(pid) and package name

After analysis of source code of Android's package manager application, i found forceStopPackage method is used by system image to kill the processes- which uses android.Manifest.permission.FORCE_STOP_PACKAGES permission.  But problem is that this permission is granted only for system level application.



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 for killBackgroundProcesses(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.
    " 


3 comments :

  1. 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
  2. @Anonymous, use the older method restartPackate() http://developer.android.com/reference/android/app/ActivityManager.html#restartPackage(java.lang.String)

    ReplyDelete

Your Comment and Question will help to make this blog better...