In this cookie blog on the android app development, Learn how to stop apps running in background android programmatically.

Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!

how to stop apps running in background android programmatically
how to stop apps running in background android programmatically

How to stop apps running in Background Android Programmatically

Kill all Apps

Firstly, killing any other app other than your own app running in the background isn’t a good idea but in case you’re building a task killer app. Here is what you can do:

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);
   } 

The ActivityManager class gives information about and interacts with, activities, services, and the containing process.

The ActivityManager.KillBackgroundProcesses have the system immediately kill all background processes associated with the given package.

Learn to build and Sell a live wallpaper app in Google Play Store, More here.

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.

Killing only My App

If you want to kill only your app (suicide is never an option!), here is what you can do:

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

mActivityManager.killBackgroundProcesses("YOUR_PACKAGE_NAME);

However, here is a small excerpt from an answer to killing background apps in android programatically, somthing you should read about:

When you see the list of running apps in apps like TaskKiller or Quick System Info, many of them are not actually running, they are just in a suspended state. These apps are not consuming system resources because Android has decided to stop them until they are needed again. However, when you kill them, you don’t give them time to shut down cleanly, and when you try to launch them next time you can be presented with an unfriendly force close dialog. I have seen apps break completely, with even a re-install being ineffective, because they are trying to read a corrupted file on the SD card, or they use unofficial API calls.

StackOverflow Sauce

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like