Android process killer
Asked Answered
B

3

15

Maybe you can help.

Is it possible to get list of all Processes which 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.

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.

Beestings answered 27/4, 2010 at 9:50 Comment(0)
M
40

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

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.

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 RUNNING on their phone, which they are often not. This is explained in the [ActivityManager docs][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 running apps 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.

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

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

freetaskmanager is an example of one of these task managers in use.

Medieval answered 27/4, 2010 at 10:32 Comment(9)
Ok, I see. Thank you for clarification. So maybe I will try to write my simple task manager.Beestings
While I agree killing processes is a bad idea, I find that on my phone it can be necessary as some applications don't provide a way of closing themselves properly and my phone can become quite slow and unreactive. Using a task killer solves this problem.Odoric
I don't agree with you in some degree. For example, some apps use Push Service in the background, which could consume system resources, or disturb users. So we need to kill these unfriendly processes.Noguchi
@Noguchi - if an app push service consumes resources excessively or disturbs your user experience, report a bug to the author and uninstall it. Killing processes is not normal operation - in fact you potentially make things worse by terminating them unexpectedly for the reasons I explained above.Medieval
@Medieval You said "Task management is the responsibility of the Android O/S". What if developers write resource hungry apps that spawn foreground processes? I don't think Android will kill those for you automatically.Clemmer
@IgorG. Android has full control of the system under normal circumstances. A resource-hungry app is still constrained within its VM, and is elegible for forced termination like any other user-space program. However, there are some cases when an app has been written to use native libraries and loopholes to evade the standard app lifecycle - for these apps you should uninstall and report a bug to the developer. The situation of a misbehaving app could be made worse by forcing it to close with a task manager.Medieval
@Medieval I hear what you are saying, but that is not how foreground services are handled in Android. Straight from the horse's mouth: "A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory."Clemmer
@IgorG. From the same source: "It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern." The responsibility is most certainly, without exception, with the Android process management. Create a foreground service that eats memory and you'll see what I mean. You might find this section an interesting read on the subject: developer.android.com/guide/components/…Medieval
I disagree with Sean`s second line that states, "Whilst it is possible to write task killer apps, it shouldn't be encouraged for anything outside of development/debugging purposes." Actually I need to do just that for an app that was requested specifically by a customer. I think it is wrong to assume all apps out there fit inside a generic prepackaged box for mass consumption by the general public. In my case shutting off system services is the only way my app can work, and it is a big deal to my customer.Bubaline
C
7
    // 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");
     }
    }
    */
Covington answered 31/12, 2010 at 5:35 Comment(2)
This will not work for the OP, because the kernel prevents android.os.Process.killProcess from killing application beyond the scope of its package.Emmons
@HeshanPerera I agree... There are a lot of old questions and answers on stackoverflow NO longer valid. For security reason, Android no long lets their user kill other apps from their app.Neo
S
3

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 order because the devices have a back button...so you dutifully call finish() or finishFromChild(childActivity)and when the user exits the app, there's a previous activity from your app, happily ignoring your code that asked it exit.

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 load my Activities to do all the heavy lifting on or near to the load events.

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

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

This example captures the Android Native back button event 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.

    @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);
    }
 }
Spancake answered 5/4, 2011 at 13:41 Comment(1)
This does not anwser the question, it shows how to kill the app, not other apps.Ameliaamelie

© 2022 - 2024 — McMap. All rights reserved.