如何通过停止应用程序的后台 运行 而退出,但不关闭服务

How to exit with stopping the background running from application but, not close services

我一直在寻找有关如何关闭 android 应用程序的解决方案。

收集所有与该主题相关的 post,我最终构建了一个健康有效的解决方案,我想在此 post

中分享

如果我在某处失败了,请指正我。

public static void closeApp(Activity activity) {
    //Go to home to change main android view and focus
    //You can remove this part
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);

    //finish in background many activities as possible
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        activity.finishAndRemoveTask();
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        activity.finishAffinity();
    } else {
        activity.finish();
    }

    //Kill all existing app process
    activity.moveTaskToBack(true);
    android.os.Process.killProcess(android.os.Process.myPid());

    //close the app
    System.exit(0);
}

使用示例

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            closeApp(MainActivity.this);
        }
    });
}

在释放资源和完全关闭应用程序方面,您使用的方法看起来非常全面。虽然我觉得它有点过头了,但如果那是你的用例所要求的,那就没问题了。您可以查看此 SO 以获得更多见解。

我对以下行有评论

stopping the background running from application but, not close services

android.os.Process.killProcess(android.os.Process.myPid()); 此方法将终止具有给定 PID 的进程。如果您的服务在此 PID 中为 运行,那么它们也会被杀死。

从 AndroidO 开始,对后台执行施加了一些限制,因此您无法在后台保留服务 运行。当您的应用程序退出时,OS 将终止服务,就像您已调用 stopSelf() 一样。因此,您将无法继续使用您的服务。