android - API v29 对从后台启动活动的限制
问题描述
我有一个ForegroundService
运行大任务的。用户可以在服务运行时按下主页按钮或导航到不同的应用程序。当服务完成或点击“触发器”时,将Intent
启动一个新的。当新的Intent
开始时,我希望应用程序回到前台(或焦点),以便用户可以继续使用该应用程序。在 API v30(我认为是 v29)之前,这很好用。我知道使用 API v29,对从后台启动活动有新的限制。限制的一个例外是“应用程序PendingIntent
从系统接收通知。在服务和广播接收器的待处理意图的情况下,应用程序可以在发送待处理意图后的几秒钟内启动活动。” 我开始新的Intent
PendingIntent
尝试利用限制异常,但这仅适用于较旧的 API 版本。此外,我会假设这两个额外的例外之一将适用:“该应用程序在前台任务的后台堆栈中有一个活动”或“该应用程序在最近屏幕上现有任务的后台堆栈中有一个活动”但我不明白为什么两者都不适用。
如何将应用程序重新置于前台或使此异常适用于 v29 及更高版本?
在以下代码中的调试消息之后,我只有在使用 API v30 时手动将应用程序重新聚焦后,才能Log
在 NewIntent.kt 中看到“onCreate in NewIntent”日志消息。onCreate
较旧的 API 版本会自动将应用程序重新聚焦并直接跳转到onCreate
NewIntent.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.
...
}
}
解决方案
推荐阅读
- mysql - azure cloud shell 工作时使用工作台访问 Azure MySQL 数据库
- javascript - Angular 2 Rxjs 在服务器响应后创建动作
- php - Google API + PHP + Ajax 调用 - 请求的资源上存在 Access-Control-Allow-Origin 标头
- python - sys.argv 列表索引超出范围错误
- html - 高度:自动扩展最小高度
- spring - 无法将类型为“java.lang.String”的属性值转换为所需类型“java.time.LocalDate”,用于百里香形式的属性“日期”
- html - 改变孩子在表格中的位置 - CSS
- javascript - JavaScript中的增量正确性递归算法
- .htaccess - Htaccess 重定向始终保留旧路径
- apache-spark - sparklyr 寻找使用时间序列的方法(hts、预测、timekit 或预言机)