0

I can terminate my application like this:

android.os.Process.killProcess(android.os.Process.myPid());

How can I terminate any application (or only the ones which allow to do that) much like the button App Info -> Force stop does?

Incerteza
  • 32,326
  • 47
  • 154
  • 261

2 Answers2

1

Firstly you cannot kill the processes your application has not created. For processes started by your application you can kill them by using

public static final void killProcess (int pid)

Docs

If you want to kill background processes you can do

public void killBackgroundProcesses (String packageName)

Docs

But you will need KILL_BACKGROUND_PROCESSES permission for that.

AFAIK this will just kill the process, but it won't kill the task in memory. So when the app is restarted, the activity stack/task will get re created from last time unless ofcourse the system itself kills it for freeing up the resources.

So AFAIK you can never achieve the same effect as App Info -> Force stop programmatically because there is no way to clear tasks in the memory and only system can do that.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
1

You can use that code to get Aplicattion PID.

 /**
 * Gets the process pid.
 *
 * @param processName the process name
 * @return the process pid
 */
public static int getProcessPid(String processName, Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> procList = null;
    int result = -1;

    procList = activityManager.getRunningAppProcesses();
    for (Iterator<RunningAppProcessInfo> iterator = procList.iterator(); iterator
            .hasNext();) {
        RunningAppProcessInfo procInfo = iterator.next();
        if (procInfo.processName.equals(processName)) {
            result = procInfo.pid;
            break;
        }
    }
    return result;
}