首页 > 解决方案 > API v29 对从后台启动活动的限制

问题描述

我有一个ForegroundService运行大任务的。用户可以在服务运行时按下主页按钮或导航到不同的应用程序。当服务完成或点击“触发器”时,将Intent启动一个新的。当新的Intent开始时,我希望应用程序回到前台(或焦点),以便用户可以继续使用该应用程序。在 API v30(我认为是 v29)之前,这很好用。我知道使用 API v29,对从后台启动活动有新的限制。限制的一个例外是“应用程序PendingIntent从系统接收通知。在服务和广播接收器的待处理意图的情况下,应用程序可以在发送待处理意图后的几秒钟内启动活动。” 我开始新的IntentPendingIntent尝试利用限制异常,但这仅适用于较旧的 API 版本。此外,我会假设这两个额外的例外之一将适用:“该应用程序在前台任务的后台堆栈中有一个活动”或“该应用程序在最近屏幕上现有任务的后台堆栈中有一个活动”但我不明白为什么两者都不适用。

如何将应用程序重新置于前台或使此异常适用于 v29 及更高版本?

在以下代码中的调试消息之后,我只有在使用 API v30 时手动将应用程序重新聚焦后,才能Log在 NewIntent.kt 中看到“onCreate in NewIntent”日志消息。onCreate较旧的 API 版本会自动将应用程序重新聚焦并直接跳转到onCreateNewIntent.kt 中的函数。

ForegroundService.kt
...
//When "trigger" is reached, start the new Intent and bring app to foreground if it was moved to background
private fun startNewActivity() {
    //First two lines are to shut down the foreground service since it has reached a trigger and is complete.
    super.onDestroy()
    stopSelf()
    
    //Start the new intent
    val startNewIntent = Intent(this, NewIntent::class.java)
    val pendingIntent = PendingIntent.getActivity(this, 0, startNewIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_ONE_SHOT)
    pendingIntent.send()
    Log.d("DEBUG", "PendingIntent sent") //App will hang here with new API version until app is manually brought back into foreground
}
...
NewIntent.kt

class NewIntent : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        Log.d("DEBUG", "onCreate in NewIntent") //Only can get here when app is manually brought back into foreground with new API version. 
        ...
    }
}

标签: androidandroid-pendingintentandroid-background

解决方案


推荐阅读