简体   繁体   English

如何终止Android应用后台进程?

[英]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. 但是,在“:anotherprocess”启动之后,我需要通过adb以某种方式杀死主进程。

I've tried "Terminate Application" in the DDMS and the main process is killed but recreated after a few seconds. 我已经在DDMS中尝试了“终止应用程序”,并且主进程被终止了,但是几秒钟后重新创建了。

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) 如果API> = 8,请使用mActivityManager.killBackgroundProcesses(String packageName)

if API < 8 use mActivityManager.restartPackage(packageInfo.packageName); 如果API <8,请使用mActivityManager.restartPackage(packageInfo.packageName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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