来自后台的 StartActivity 方法

StartActivity method from background

问题似乎已知,但我找不到正确的解决方案。


我来描述场景:


有一个应用程序向 API 发出请求。在某些 FirstActivity 中,向 API 发出请求,如果结果为肯定,则在 SecondActivity 中调用 startActivity()。问题是,如果在发送请求的时候,应用程序被最小化到后台(即后台会调用startActivity()),那么:

  1. 如果android版本>=29那么startActivity()基本就不行了。 startActivity () finish () 之后的一个将起作用,并且在重新启动应用程序时将重新启动(这是合乎逻辑的)
  2. 如果 android 版本 < 29,则 startActivity() 将触发并将此 SecondActivity 带到前台。

基于此,问题是。我如何强制应用程序(无论版本如何)在活动之间转换而不将它们带到前台?

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
            finish();

根据文档

Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background.

解决方法:在特定情况下,您的应用可能需要紧急引起用户的注意,例如正在进行的闹钟或来电.您之前可能已为此目的配置了您的应用程序,方法是在您的应用程序处于后台时启动 activity。

要在 运行 Android 10(API 级别 29)或更高级别的设备上提供类似的行为,请完成此 guide.[=14 中描述的步骤=]

您可以显示具有全屏意图的高优先级通知。

More Details

新要求的更新答案:征求意见 (好吧,请告诉我如何让 startActivity() 在后台启动 activity 也在后台,而不是从后台启动应用程序)

您可以添加一个 LifecycleObserver,它将在 LifecycleOwner 更改状态时收到通知。

在您的 activity api 响应回调中使用以下条件

if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
            // Activity is in resumed state, Open new activity immediately
        } else {
            // else add a LifecycleObserver that will be notified when the LifecycleOwner changes state
            lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onStart(owner: LifecycleOwner) {
                    super.onStart(owner)
                    // remove observer immediately so that it will not get triggered all the time
                    lifecycle.removeObserver(this)
                    // Activity is in start state again, Open new activity here
                }
            })
        }