【发布时间】:2019-08-14 18:35:18
【问题描述】:
我一直面临有关 startActivity(intent) 的问题。我正在开发的是一种关键字检测,如“ok google”,当用户说出这个词时会触发警报。为了在用户不使用应用程序时实现这一点,我有一个 LifecycleService 在前台运行并监听用户。当用户说出这个词并且应用程序被杀死时,它会使用服务中的 startActivity 打开我需要的活动,但问题是如果我继续收听并更改为其他活动(正常使用应用程序),检测工作正常(因为我听到我在识别单词时发出的声音)但应用程序没有启动它应该启动的活动(尽管调用了 startActivity(intent))。我很确定当我从服务中使用 startActivity 打开应用程序时,问题必须与可能不是正确的上下文有关,但我不知道如何解决它。我尝试使用其他一些变量,例如 Koin 的 applicationContext 或 androidContext() ,但它不起作用。
class SpeechRecognitionService : LifecycleService() {
...
//onStartCommand starts the audio recognizer and startAlert() is triggered when the alert is recognized. It is always correctly called
private fun startAlert() {
//This is not showing MainActivity although i execute it
startActivity(MainActivity.getDialogIntent(this))
//I always hear this audio when the app detects word
val audio = MediaPlayer.create(this, R.raw.alert_detected_audio)
audio.start()
}
}
MainActivity.getDialogIntent(this) 只是一个普通的 Intent
fun getDialogIntent(context: Context): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.putExtra(SHOW_ALERT_DIALOG_KEY, true)
return intent
}
该问题仅在应用程序以语音识别启动时发生(在被杀死后)。例如,如果我杀死应用程序但再次按应用程序图标打开应用程序,它可以正常工作。如果我用语音启动应用程序(所以,从我上面的 startActivity 开始)我当时工作并打开应用程序,但是当我更改为其他活动时它无法启动。
【问题讨论】:
标签: android service android-lifecycle android-context intentservice