0

I would like to stop an app programmatically. I read that should be done calling to moveTaskToBack() but I can't figure how can I call it based on a package name like "com.adobe.reader" . I can find his persistent task id searching in the task stack but I don't know what to do now.

public static void stopPackageProcess(String packageName, Context context) {

    Context mContext = context;

    final ActivityManager am = (ActivityManager) mContext
        .getSystemService(Context.ACTIVITY_SERVICE);

    List<ActivityManager.RecentTaskInfo> mTasks =
        am.getRecentTasks(Integer.MAX_VALUE, ActivityManager.RECENT_IGNORE_UNAVAILABLE);

    for (int i = 0; i < mTasks.size(); i++)
    {
        String name = mTasks.get(i).baseIntent
            .getComponent().getPackageName();

        if(name.equals(packageName)) {
            // TODO: Stop App
            break;
        }
    }
}
joao2fast4u
  • 6,868
  • 5
  • 28
  • 42
juan ezquerro
  • 145
  • 2
  • 12

2 Answers2

3

If you get you right, you want to stop an app in the background.

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am.killBackgroundProcesses(PACKAGENAME);

does this. to example This need the android.permission.KILL_BACKGROUND_PROCESSES permission

GGG
  • 35
  • 4
  • not really, i would like to stop an app that is already running, as music player by example, a move to background so the user can restart the app again from recents view – juan ezquerro May 18 '14 at 14:22
  • I found another answers is better which can kill all of my apps and wait for done (https://stackoverflow.com/a/12508376/1074998 ) – 林果皞 Jul 25 '17 at 12:06
0

You can't kill just any process in Android. From the documentation on Process:

Note that, though this API allows us to request to kill any process based on its PID, the kernel will still impose standard restrictions on which PIDs you are actually able to kill. Typically this means only the process running the caller's packages/application and any additional processes created by that app; packages sharing a common UID will also be able to kill each other's processes.

Also note that the permission you're requesting in your manifest doesn't work the way you think it does. According to the documentation, KILL_BACKGROUND_PROCESS:

Allows an application to call killBackgroundProcesses(String).

Santhi Bharath
  • 2,818
  • 3
  • 28
  • 42
  • well, i'm not writing an app, i'm modifying AOSP so i can kill any process. Actually i kill processes based on package name with ActivityManager.removeTask() and ActivityManager.REMOVE_TASK_KILL_PROCESS but it removes it from recent views and that is what i want to avoid. – juan ezquerro May 18 '14 at 15:53