简体   繁体   中英

How to kill an Android app background process?

I have an app with two processes. The second process starts when an Activity is created. Find below an excerpt of that Activity in the Manifest:

    <activity
        android:name=".ActivityInAnotherProcess"
        android:process=":anotherprocess"
        android:launchMode="singleTask"
        ...

After the ":anotherprocess" starts I need to kill the main process somehow, through the adb, in code, however.

I've tried "Terminate Application" in the DDMS and the main process is killed but recreated after a few seconds.

I've tried this code:

String packageName = c.getPackageName();
ActivityManager activityManager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(packageName);

but the main process is killed only to be recreated after a few seconds.

UPDATE: The code posted above works. I was calling it a few seconds after starting the Activity in the other process but it seems the other process was not fully started before I killed the main process. Now I'm killing the main process from the other process. This works now. Thanks all!

List<ApplicationInfo> packages;
PackageManager pm;
pm = getPackageManager();
packages = pm.getInstalledApplications(0);

ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);


for (ApplicationInfo packageInfo : packages) {
    if((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM)==1)continue;
    if(packageInfo.packageName.equals("mypackage")) continue;
    mActivityManager.restartPackage(packageInfo.packageName);
} 

if API >= 8 use mActivityManager.killBackgroundProcesses(String packageName)

if API < 8 use mActivityManager.restartPackage(packageInfo.packageName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM