当我们收到通知时,如何使用后台服务启动警报?当我的应用程序处于活动状态时,后台服务很容易启动,但当应用程序处于后台时,后台服务器就无法运行。
1。为什么会发生这种情况
FCM(Firebase Cloud Messaging(中有两种类型的消息:
显示消息:只有当您的应用程序处于前台时,这些消息才会触发onMessageReceived((回调
数据消息:这些消息触发onMessageReceived((回调,即使您的应用程序处于前台/后台/已终止
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// ...
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be:
Log.d(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob()
} else {
// Handle message within 10 seconds
handleNow()
}
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}