android – Kill another process/application programmatically-ThrowExceptions

Exception or error:

I don’t want to get on the discussion of whether a process can be killed by the user, whether it should be done that way or not.

I just want to know how almost every Android player’s phone got a ‘advanced task killer‘ which kills a process or how is it that the force close (in settings) option works just fine. I have tried many ways to kill a process, but all without result. But when I see these ‘advanced task killer‘ I can’t figure out what’s wrong on my side.

How to solve:

You can use the killBackgroundProcesses() method of ActivityManager:

    ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
    am.killBackgroundProcesses(packageName);

Please, note that your app needs to own the KILL_BACKGROUND_PROCESSES permission. Thus, in the AndroidManifest.xml, you need to include:

<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />

###

Try android.os.Process:

void killMyProcess() {
    android.os.Process.killProcess(android.os.Process.myPid());
}

As it implies from the method name, you can only kill your own process by using this approach.

###

Suppose you have launched activities in the order A -> B -> C -> D with A as your main and launcher activity.

You can not even kill your application’s process by calling Process.KillProcess(int pid) method in your D activity. You need to kill each activity D – C – B – A (in reverse order) to kill the process.

So killing other application processes is out of the question.

Leave a Reply

Your email address will not be published. Required fields are marked *