我有一个
以下是相关的代码部分:
ForegroundService
,需要一些时间来运行。在此期间,用户可能会将应用程序移到后台,例如按下主页按钮或进入其他应用程序。当ForegroundService
达到“触发器”时,它尝试启动一个新的意图。如果应用程序在前台运行,则这很好,但如果在后台运行,则无法正常工作。目标是当达到“触发器”时,应用程序将返回到前台,以便用户可以在新的意图中提供所需的输入。为此,我添加了FLAG_ACTIVITY_NEW_TASK
和FLAG_ACTIVITY_SINGLE_TOP
标志,因为它们看起来可以完成此操作。但是,应用程序没有回到前台。是否可以做到这一点?以下是相关的代码部分:
MainActivity.kt
...
private fun startService() {
val serviceIntent = Intent(this, ForegroundService::class.java)
ContextCompat.startForegroundService(this, serviceIntent)
}
...
ForegroundService.kt
...
//When trigger is reached, start the new activity 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)
startNewIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP //Assumption was these flags would bring app to foreground
startActivity(startNewIntent)
}
...