Android – force closes the application programmatically

I need to create an application that can programmatically execute the force stop button to perform operations on the application. (I'm using root privileges)

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

The problem is that the process cannot be found even if the forced stop button is not grayed out

Even use:

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


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

                        os.flush();

When this code is executed, the forced stop button will not be grayed out

How can root programmatically execute the force stop button in app info?

resolvent:

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 the name of the application package that is forced to stop

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>