强制关闭一个应用程序编程应用程序

2023-09-05 04:58:21 作者:素颜、打造雕像

我需要做一个应用程序,可以编程做什么,在力停止按钮确实给应用程序。 (我用的根权限)

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

我已经试过这code:

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

但问题是找不到的过程中,即使力停止按钮的不是变灰。

即使使用:

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


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

                        os.flush();

不执行力停止按钮的功能,因为在我执行此$ C C力停止按钮$什么的不是变灰。

使用根我该怎么编程做在App信息的力量停止按钮呢?

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

推荐答案

我找到了解决方法:

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