is it possible to close apps programatically which are running in background in android? [duplicate]

人走茶凉 提交于 2019-11-30 07:42:57

问题


I want to stop or close apps which are running in background in android. Is it possible? If so how to achieve this. Refer any links will be appreciated.

Thanks in advance..


回答1:


You can use Process.killProcess(int pid) to kill processes that have the same UID with your App. You can use ActivityManager.killBackgroundProcesses(String packageName),with KILL_BACKGROUND_PROCESSES permission in your manifest(for API >= 8) or ActivityManager.restartPackage (String packageName)(for API < 8) to kill specified process,except of forground process.

So if you would to kill all other processes when your program is foreground process,you would to use ActivityManager.killBackgroundProcesses or ActivityManager.restartPackage:

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

    ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);

   for (ApplicationInfo packageInfo : packages) {
        if((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM)==1)continue;
        if(packageInfo.packageName.equals("mypackage")) continue;
        mActivityManager.killBackgroundProcesses(packageInfo.packageName);
   }   

In above snippet code,each process will be killed unless it be process of your App or system process.



来源:https://stackoverflow.com/questions/23927405/is-it-possible-to-close-apps-programatically-which-are-running-in-background-in

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