How to close third party apps by my own app on Android

1.6k views Asked by At

I'm working in app to monitoring how much long a child can play a game in a Android device.

I know how to get a list of runnings apps using:

List<RunningTaskInfo> tasks = activityManager.getRunningTasks(1);//Integer.MAX_VALUE

Now I want a way to close this app, or just put it in background.

Take a look at my code:

private void verifyIfHasToCloseAnyApp() {
    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = activityManager.getRunningTasks(1);//Integer.MAX_VALUE
    List<AppBlocked> appBlockeds = listAllAppBlocked();

        for (RunningTaskInfo runningTaskInfo : tasks) {

            String packageName = runningTaskInfo.topActivity.getPackageName();

            for(AppBlocked appBlocked : appBlockeds) {
                String packageBlocked = appBlocked.getAppPackage();
                if(packageName.equals(packageBlocked)) {
                    if(appBlocked.isTimeToClose())
            /*Here I have to close or put this app in background */
                }   
            }

        }
}

Is it possible?

Thanks.

1

There are 1 answers

0
Adam Radomski On

You cannot do this via standard api. Edit Or you can: https://stackoverflow.com/a/7197265/1434792

You can execute ps command by

Process process = Runtime.getRuntime().exec("ps");

and than find pid of process that you want to kill in output of this command and then run kill command with this pid.

    Process process = Runtime.getRuntime().exec("kill " + pid);

Propably you need to have root access to do this but im not sure about it. If you need this than kill this process by

        Process process = Runtime.getRuntime().exec("su");

        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        InputStream is = process.getInputStream();
        os.writeBytes("kill " + pid+ "\n");
        int readed = 0;
        byte[] buff = new byte[4096];
                    os.writeBytes("exit\n");
        os.flush();
                process.destroy();