Android ActivityManager killBackgroundProcess not working

為{幸葍}努か 提交于 2019-12-05 12:39:34

Make sure you are targeting API level 8, as that method was only added in Android 2.2.

The method signature is

public void killBackgroundProcesses (String packageName)

Not

public void killBackgroundProcess (int processID)

The following is working CODE :

public static void killThisPackageIfRunning(final Context context, String packageName){
    ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
    activityManager.killBackgroundProcesses(packageName);
}   

But this works only for >= API Level 8 as this method was added in Android 2.2.

james

The argument is package Name not processId. Try passing it something like:

myActivity.getApplication().getPackageName()

as an argument.

Be sure that your calling killBackgroundProcesses with the topmost Activity.

You can try these codes below, it works for me .

public static void clearMemory(Context context) {
        ActivityManager activityManger = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> list = activityManger.getRunningAppProcesses();
        if (list != null)
            for (int i = 0; i < list.size(); i++) {
                ActivityManager.RunningAppProcessInfo apinfo = list.get(i);

                String[] pkgList = apinfo.pkgList;

                if (apinfo.importance > ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE ) {
                    for (int j = 0; j < pkgList.length; j++) {
                        activityManger.killBackgroundProcesses(pkgList[j]);
                    }
                }
            }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!