2

I want to stop or close apps which are running in background in android. Is it possible? If so how to achieve this. Refer any links will be appreciated.

Thanks in advance..

Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
  • @Pankaj Kumar In that question they not clearly mentioned code to achieve this. See the accepted answer It is different from what you thinking.. – Shailendra Madda May 29 '14 at 07:23
  • 2
    Don't be too ironic. The question you have asked has been asked too many times on SO with a code too. So first search for existing solution. Few threads are http://stackoverflow.com/questions/9804786/how-to-kill-a-3rd-party-application , http://stackoverflow.com/questions/12892400/get-running-processes-list-and-kill-their-background-services and http://stackoverflow.com/questions/2720164/android-process-killer. – Pankaj Kumar May 29 '14 at 07:32

1 Answers1

14

You can use Process.killProcess(int pid) to kill processes that have the same UID with your App. You can use ActivityManager.killBackgroundProcesses(String packageName),with KILL_BACKGROUND_PROCESSES permission in your manifest(for API >= 8) or ActivityManager.restartPackage (String packageName)(for API < 8) to kill specified process,except of forground process.

So if you would to kill all other processes when your program is foreground process,you would to use ActivityManager.killBackgroundProcesses or ActivityManager.restartPackage:

List<ApplicationInfo> packages;
    PackageManager pm;
    pm = getPackageManager();
    //get a list of installed apps.
    packages = pm.getInstalledApplications(0);

    ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);

   for (ApplicationInfo packageInfo : packages) {
        if((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM)==1)continue;
        if(packageInfo.packageName.equals("mypackage")) continue;
        mActivityManager.killBackgroundProcesses(packageInfo.packageName);
   }   

In above snippet code,each process will be killed unless it be process of your App or system process.

Soumil Deshpande
  • 1,622
  • 12
  • 14