大佬们,有个任务,不知道怎么处理。override onHandleIntent
有一个方法try catch
,我需要把输出AlertDialog
,如何正确地做,我不知道,因为这里没有接口(+原来我必须敲活动)?
班级代码
class GcmRegistrationIntentService : IntentService("GcmRegistrationIntentService") {
override fun onHandleIntent(intent: Intent?) {
try {
val gcmSenderId = FlavorSettings.gcmSenderId
val systemToken = if (gcmSenderId.isEmpty()) gcmSenderId
else InstanceID.getInstance(this).getToken(gcmSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null)
if (PreferenceRepository.gcmToken != systemToken) {
PreferenceRepository.gcmToken = systemToken
if (UserSession.isUserSignedIn() && ProfilesRepository.lastProfile() != null) {
JobManager.scheduleAutoSync()
}
}
} catch (e: Exception) {
e.log()
}
}
}
来自的对话框输出
Service
是一种反模式。根据定义,服务是应该在后台工作的东西,并且自然地试图将某些东西从它带到 UI 级别看起来,说得客气一点,值得怀疑。推荐选项:
Activity
并已经Activity
处理了对话。但如果它真的很痒,那就看看哈布雷提供的生活窍门
更新
关于黑客,我只会用一句话
EventBus/otto/rxJava
来回答:粗略地翻译一下,这意味着无法保证应用程序和服务始终在同一个进程中。
如果是这样,那么有时可能会成功,但这可能不是我们想要的,不是吗
Activity-Service
?EventBus
评论中的想法实际上非常好。
在你的服务中,使用 EventBus 来敲类:
在 ErrorEvent 类本身中,根据您的需要,添加必要的字段。
好吧,那么,你想在 onEvent 方法中放置你的 AllertDialog 的地方(片段/活动),将这个空类的参数传递给它(也值得将 ThreadMode.MAIN 添加到注释中):
好吧,不要忘记在这个类中的方法中
onStart
实现:在方法中
onStop
:更新:
由于 Android 默认情况下将应用程序的工作构建到一个进程中,因此您不必担心它们运行在不同的进程中。如果不确定,请
AndroidManifest.xml
查看应用程序中的属性process
并确保没有差异。