1

I want to close current foreground app in Android service. However, it does not work in service. Could you have me to fix it? Thanks.

        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
        List<ApplicationInfo> packages;
        PackageManager pm;
        pm = getPackageManager();
        //get a list of installed apps.
        packages = pm.getInstalledApplications(0);

        ActivityManager mActivityManager = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String myPackage = getApplicationContext().getPackageName();
        for (ApplicationInfo packageInfo : packages) {
            if((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM)==1)continue;
            if(packageInfo.packageName.equals(myPackage )) {
                Log.d(TAG,"*************"+packageInfo.packageName);
                mActivityManager.killBackgroundProcesses(packageInfo.packageName);
            }
        }

It also went to function killBackgroundProcesses but it does not close my current foreground app. I am running in Android L with permission

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
Jame
  • 3,746
  • 6
  • 52
  • 101
  • Check this http://stackoverflow.com/questions/6733311/android-killing-all-foreground-running-app – Tasneem Nov 25 '16 at 05:33

1 Answers1

1

You are trying to kill background process in your code

mActivityManager.killBackgroundProcesses(packageInfo.packageName);

You should use:

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

Change with above one and check.

To kill other apps is kind of thing is a serious security concern so is regulated heavily. You can only kill a process that has the same package id as the one that is doing the killing. If you are trying to kill your own process it will work for other apps you can't do it(unless you have a rooted device and your application has root privileges).

You can refer this link for more info.

Community
  • 1
  • 1
Ready Android
  • 3,529
  • 2
  • 26
  • 40
  • 1
    But my input is a package name. I want to kill the package name for example `com.google.android.googlequicksearchbox` – Jame Nov 25 '16 at 04:51
  • 1
    If you want to kill your own app then it will work because myPid is your app package id or if you want to kill other apps then let me check with other solution. – Ready Android Nov 25 '16 at 04:53
  • 1
    Right. I want to kill the other apps, instead of my app – Jame Nov 25 '16 at 04:54
  • As per your code, you are trying to kill your own app not others. – Ready Android Nov 25 '16 at 05:15
  • Your code is killing the background app but not removing from the tray and I think removing from tray is in the bound of security. – Ready Android Nov 25 '16 at 05:32