How to kill all running applications in android?

后端 未结 4 560
情深已故
情深已故 2020-11-30 01:24

I want to kill all running applications in android .so for this task , i implemented following code. But it is not working .App still remains in running.

Act         


        
4条回答
  •  余生分开走
    2020-11-30 02:11

    • 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 packages;
        PackageManager pm;
        pm = getPackageManager();
        //get a list of installed apps.
        packages = pm.getInstalledApplications(0);
    
       ActivityManager mActivityManager = (ActivityManager)context.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)) continue;
            mActivityManager.killBackgroundProcesses(packageInfo.packageName);
       }      
    

    In above snippet code,each process will be killed unless it be process of your App or system process.
    References:
    How to close all active applications from my Android app?
    How do task killers work?

提交回复
热议问题