How to close foreground app in Android service?

白昼怎懂夜的黑 提交于 2019-12-23 04:54:29

问题


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" />

回答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.



来源:https://stackoverflow.com/questions/40797866/how-to-close-foreground-app-in-android-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!