Force Close an app programmatically

SamJ picture SamJ · Oct 3, 2014 · Viewed 15.6k times · Source

I need to make an application that can programmatically do what the force stop button does to applications. (I am using root permissions)

ScreenShot

I have tried this code:

private void killApp(){
    try {
        int pid = getPid(com.XXX);
        if(pid != -1){
            String command = "kill "+pid;
            Log.i("Got PID",pid + "");
            try {
                Process suProcess = Runtime.getRuntime().exec("su");
                DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

                os.writeBytes(command + "\n");
                os.flush();

                Log.i("Executed","Kill " + pid);
            } catch (IOException e) {
                // Handle error
            }   
        } else {
            Log.i("Not Found","App Not Found");
        }
    } catch (Exception e) {
        e.printStackTrace();  // Device not rooted! 
    }
}

private int getPid(String packageName){
    ActivityManager am = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();
    int processid = 0;
    for(int i = 0; i < pids.size(); i++) {
        ActivityManager.RunningAppProcessInfo info = pids.get(i);

        Log.i("PID",pids.get(i) + "");
        Log.i("PID Package",info.processName);

        if(info.processName.equalsIgnoreCase(packageName)){
            processid = info.pid;
            return processid;
        } 
    }
    return -1;
}

But the problem is that the process isn't found, even though the force stop button isn't grayed out.

Even Using:

                         Process suProcess = Runtime.getRuntime().exec("su");
                        DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());


                        os.writeBytes("kill "+ APP_PID + "\n");

                        os.flush();

Doesn't do what the force stop button does since after i execute this code the force stop button isn't grayed out.

Using root how can I programmatically do what the force stop button in the App info does?

Answer

SamJ picture SamJ · Oct 3, 2014

I found a solution:

Process suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

os.writeBytes("adb shell" + "\n");

os.flush();

os.writeBytes("am force-stop com.xxxxxx" + "\n");

os.flush();

Where com.xxxxxx is package name of application to force stop.