Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

How to kill all running applications in android?

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.

ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningAppProcessInfo service : manager.getRunningAppProcesses()) {
    Log.i("process name " , service.processName);

    android.os.Process.killProcess(service.pid);
    }

So where does i make mistake in code ? Is there any help ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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);
   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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...