如何以编程方式强制停止使用 Java 的 Android 应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29887429/
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-11 08:46:44  来源:igfitidea点击:

How can I programmatically force stop an Android app with Java?

javaandroidprocess

提问by Mitte

How can I force stop an app with Java? I'm trying to build a memory cleaner that can help clean out background processes.

如何使用 Java 强制停止应用程序?我正在尝试构建一个内存清理器,可以帮助清理后台进程。

I know there is a way to kill the process of an app, but when you go to the running list, the app is still there even after you have killed it. And I have tried a lot of similar memory cleaning apps, only one of them can totally force stop apps but it has so many useless notifications - very annoying.

我知道有一种方法可以杀死应用程序的进程,但是当您转到运行列表时,即使您将其杀死,该应用程序仍然存在。而且我尝试了很多类似的内存清理应用程序,其中只有一个可以完全强制停止应用程序,但它有很多无用的通知 - 非常烦人。

P.S.: When you go to Settings -> Apps, you will see a list of apps. Click on one of these apps and you end up on the app's info. There is a button named "force stop". By clicking on it, the app is killed. I want to perform that kind of action in my app. How can this be done?

PS:当您进入设置-> 应用程序时,您会看到一个应用程序列表。单击这些应用程序之一,您最终会看到该应用程序的信息。有一个名为“强制停止”的按钮。通过单击它,该应用程序将被杀死。我想在我的应用程序中执行这种操作。如何才能做到这一点?

force stop example

强制停止示例

采纳答案by Jeffy Lazar

get the process ID of your application, and kill that process onDestroy() method

获取应用程序的进程 ID,并通过 onDestroy() 方法终止该进程

@Override
public void onDestroy()
 {
    super.onDestroy();

    int id= android.os.Process.myPid();
    android.os.Process.killProcess(id);
 }

or

或者

getActivity().finish();
System.exit(0);

and if you want to kill other apps from your activity, then this should work

如果你想从你的活动中杀死其他应用程序,那么这应该有效

You can send the signal using:

您可以使用以下方式发送信号:

Process.sendSignal(pid, Process.SIGNAL_KILL);

To completely kill the process, it's recommended to call:

要完全终止进程,建议调用:

ActivityManager.killBackgroundProcesses(packageNameToKill)

before sending the signal.

在发送信号之前。

Please, note that your app needs to own the KILL_BACKGROUND_PROCESSES permission. Thus, in the AndroidManifest.xml, you need to include:

请注意,您的应用需要拥有 KILL_BACKGROUND_PROCESSES 权限。因此,在 AndroidManifest.xml 中,您需要包含:

<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />

回答by Santosh Shinde

Try to use following code

尝试使用以下代码

    finish(); // for stopping Current Activity

    // add this line for Removing Force Close

    @Override
        protected void onDestroy() {
    // closing Entire Application
            android.os.Process.killProcess(android.os.Process.myPid());
            super.onDestroy();
        }
    }

May be this solution will help you Force Close an app programmatically

可能是这个解决方案将帮助您以编程方式强制关闭应用程序