【问题标题】:How to exit with stopping the background running from application but, not close services如何在停止从应用程序运行的后台但不关闭服务的情况下退出
【发布时间】:2018-12-11 12:24:46
【问题描述】:

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

收集所有涉及该主题的帖子,我最终构建了一个健康有效的解决方案,我想在这篇文章中分享

如果我在某个地方失败了,请纠正我。

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);
        }
    });
}

【问题讨论】:

  • 您想为自己的应用程序或其他应用程序执行此操作?
  • 此解决方案适用于我自己的应用程序
  • 那么你想做什么?您要关闭其他应用程序吗?或者您想在不关闭服务的情况下关闭所有活动。
  • 这是一个解决方案,我花了 5 个月的时间来理解和开发它,所以我分享它以确保没有人会犯这个错误。我想知道我的代码是否有误。
  • 对于我自己的应用程序,我认为这也是一个解决方案。 Intent i=new Intent(this,FinishActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);开始活动(一);在完成活动 onCreate(){ finish(); }

标签: android exit back-button-control


【解决方案1】:

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

我对下面这行有意见

停止从应用程序运行后台,但不关闭服务

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

从 Android O 开始,对后台执行施加了一些限制,因此您无法让服务在后台运行。当您的应用程序退出时,操作系统将终止服务,就好像您调用了stopSelf()。因此,您将无法让您的服务保持活力。

【讨论】:

  • 我使用这篇文章来防止服务停止:stackoverflow.com/questions/35747624/…
  • 它的设备特定的。我在三星上观察到的最长持续时间约为 10 分钟。在谷歌像素上它不到 1 分钟。后台进程的关闭不容易控制
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2010-09-20
相关资源
最近更新 更多