Android进程杀手

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2720164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:04:57  来源:igfitidea点击:

Android process killer

androidprocess

提问by Martin

Maybe you can help.

也许你可以帮忙。

Is it possible to get list of all Processeswhich are running in the Android system, and kill some of them? I know that there are some applications (task managers), but I would like to write my own, simple application.

是否有可能获得所有Processes在 Android 系统中运行的列表,并杀死其中的一些?我知道有一些应用程序 ( task managers),但我想编写自己的简单应用程序。

I would like to write simple task manager, just list of all processes and button which will kill some of them.

我想写一个简单的任务管理器,只列出所有进程和按钮,这些进程和按钮会杀死其中的一些。

Could you just write some Java methods which I can call in order to get list of process, and method for killing them. Or just give me some advice's.

你能不能写一些我可以调用的Java方法来获取进程列表,以及杀死它们的方法。或者只是给我一些建议。

回答by seanhodges

Killing apps/services in Android is generally a really bad idea. Whilst it is possible to write task killerapps, it shouldn't be encouraged for anything outside of development/debugging purposes.

在 Android 中杀死应用程序/服务通常是一个非常糟糕的主意。虽然可以编写task killer应用程序,但不应鼓励出于开发/调试目的之外的任何事情。

Task management is the responsibility of the Android O/S, the tasks you can see are not processes(in the sense of the processes you see in the Windows task manager for example), in fact, they only have a process when Android tells them they can have one.

任务管理是Android O/S的职责,你看到的任务不是进程(比如你在Windows任务管理器中看到的进程),实际上只有Android告诉他们的时候才有进程他们可以有一个。

Apps are regularly broken by these task management tools, as they often fail to recover from the forced termination, particularly if they were busy writing to a file or using another resource when they were killed. It also puts the handset users into a false expectation that the apps listed are actually RUNNINGon their phone, which they are often not. This is explained in the [ActivityManager docs][1]:

应用程序经常被这些任务管理工具破坏,因为它们经常无法从强制终止中恢复,特别是当它们被杀死时正忙于写入文件或使用其他资源时。它还让手机用户误以为列出的应用程序实际上正在他们的手机上运行,而他们通常不是。[ActivityManager 文档][1] 对此进行了解释:

Information you can retrieve about a particular task that is currently "running" in the system. Note that a running task does not mean the given task actual has a process it is actively running in; it simply means that the user has gone to it and never closed it, but currently the system may have killed its process and is only holding on to its last state in order to restart it when the user returns.

您可以检索有关当前在系统中“运行”的特定任务的信息。请注意,正在运行的任务并不意味着给定的任务实际有一个正在积极运行的进程;它只是意味着用户已经去了它并且从未关闭它,但是目前系统可能已经终止了它的进程并且只保持它的最后状态以便在用户返回时重新启动它。

When you see the list of runningapps in apps like TaskKiller or Quick System Info, many of them are not actually running, they are just in a suspended state. These apps are not consuming system resources because Android has decided to stop them until they are needed again. However, when you kill them, you don't give them time to shut down cleanly, and when you try to launch them next time you can be presented with an unfriendly force close dialog. I have seen apps break completely, with even a re-install being ineffective, because they are trying to read a corrupted file on the SD card, or they use unofficial API calls.

当您running在 TaskKiller 或 Quick System Info 等应用程序中看到应用程序列表时,其中许多实际上并未运行,它们只是处于挂起状态。这些应用程序不会消耗系统资源,因为 Android 已决定停止它们,直到再次需要它们为止。但是,当您杀死它们时,您不会给它们时间完全关闭,并且当您下次尝试启动它们时,您可能会看到一个不友好的强制关闭对话框。我见过应用程序完全崩溃,即使重新安装也无效,因为它们试图读取 SD 卡上损坏的文件,或者它们使用非官方 API 调用。

In short, friends don't let friends use task killers in Android.

总之,朋友不要让朋友在Android中使用任务杀手。

Anyway, to answer your question, the ActivityManageris what most of these apps use to list activities that are in running/suspended state.

无论如何,为了回答您的问题,ActivityManager这些应用程序中的大多数用于列出处于运行/暂停状态的活动。

freetaskmanageris an example of one of these task managersin use.

freetaskmanager是其中一个正在使用的示例task managers

回答by Kevin Li

    // Get currently running application processes
    List<ActivityManager.RunningAppProcessInfo> list = servMng.getRunningAppProcesses();
    if(list != null){
     for(int i=0;i<list.size();++i){
      if("com.android.email".matches(list.get(i).processName)){
       int pid = android.os.Process.getUidForName("com.android.email");
             android.os.Process.killProcess(pid);
      }else{
       mTextVIew.append(list.get(i).processName + "\n");
      }
     }
    }


    /*
    // Get currently running service
    List<ActivityManager.RunningServiceInfo> list = servMng.getRunningServices(1024);
    if(list != null){
     for(int i=0;i<list.size();++i){
      mTextVIew.append(list.get(i).service.getClassName() + "\n");
     }
    }
    */

    /*
    // Get currently running tasks
    List<ActivityManager.RunningTaskInfo> list = servMng.getRunningTasks(1024);
    if(list != null){
     for(int i=0;i<list.size();++i){
      mTextVIew.append(list.get(i).toString() + "\n");
     }
    }
    */

回答by Rob

Exiting an Android App via Java is tricky to say the least. Killing the app via the Process Object interface is generally considered bad form for all the reasons listed above, I wont rehash them, but I don't feel that the published discouragements are meant to stop you from doing it all together, they just make you aware of possible caveats. Here's the catch, Android has to keep track of Activities and load/run orderbecause the devices have a backbutton...so you dutifully call finish()or finishFromChild(childActivity)and when the user exitsthe app, there's a previous activity from your app, happily ignoring your code that asked it exit.

通过 Java 退出 Android 应用程序至少可以说是棘手的。由于上面列出的所有原因,通过 Process Object 接口杀死应用程序通常被认为是不好的形式,我不会重复它们,但我不认为发布的劝阻是为了阻止你一起做这一切,它们只会让你意识到可能的警告。这里有一个问题,Android 必须跟踪活动,并且load/run order因为设备有一个back按钮......所以你尽职尽责地调用finish()finishFromChild(childActivity)当用户exits使用应用程序时,你的应用程序有一个以前的活动,愉快地忽略要求它退出的代码。

Sometimes, you just have to kill the app. So...before committing this digital process kill, you have to do a little planning. Make sure the user won't be killing any file I/O or network communication vital to your app. My strategy for this was to front loadmy Activities to do all the heavy lifting on or near to the load events.

有时,您只需要杀死该应用程序。所以......在进行这个数字化进程终止之前,你必须做一些计划。确保用户不会终止对您的应用至关重要的任何文件 I/O 或网络通信。我对此的策略是让front load我的活动在负载事件上或附近完成所有繁重的工作。

Also, I always prompt the user before they exit, a desktop application UI convention that translates well here.

此外,我总是在用户退出之前提示用户,这是一种桌面应用程序 UI 约定,在这里翻译得很好。

The above code misses the mark by calling "getUidForName"...

上面的代码通过调用“getUidForName”错过了标记......

This example captures the Android Native back buttonevent from the hardware back button and prompts the user "do you really want to leave my app" and if the user selects "yes" it kills the App.

此示例back button从硬件后退按钮捕获 Android Native事件并提示用户“你真的想离开我的应用程序吗”,如果用户选择“是”,它会终止应用程序。

    @Override 
public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if(keyCode == KeyEvent.KEYCODE_BACK) {
        //Ask the user if they want to quit
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.exclamationpoint)
        .setTitle("Exit?")
        .setMessage("You are about to exit the Application. " + 
                     "Do you really want to exit?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
             @Override
            public void onClick(DialogInterface dialog, int which) {
                //Stop the activity
                 //maintenancetabs.this.finish();
                 int pid = android.os.Process.myPid();
                 android.os.Process.killProcess(pid);
                }
         })
        .setNegativeButton("No", null)
        .show();
         return true;
    }     else {
        return super.onKeyDown(keyCode, event);
    }
 }