【发布时间】:2021-01-13 14:01:28
【问题描述】:
当应用程序从FCM 接收到push notification 时,它会调用onMessageReceived。 (见1、2 或3。)
当用户点击通知时,它会启动应用程序,然后向服务器发送用户已阅读通知的请求。
我想知道设备何时收到推送通知,但用户刷了它(或清除了所有通知)。我想向服务器发送一个请求,用户只是取消了通知。
我尝试发送BroadcastReceiver 并显示日志(请参阅4 或5),但它在应用程序在通知传递时打开时工作。我想,那个
MyFirebaseMessagingService:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
...
// An event when a user swipes a notification.
val intent = Intent(this, NotificationBroadcastReceiver::class.java)
intent.action = "notification_cancelled"
val deleteIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
notificationBuilder.setDeleteIntent(deleteIntent)
// Navigation to an activity when a user taps the notification.
// It doesn't matter to this question.
val intent2 = Intent(this, MainActivity::class.java)
val navigateIntent = PendingIntent.getActivity(this, notificationId, intent2,
PendingIntent.FLAG_UPDATE_CURRENT)
notificationBuilder.setContentIntent(navigateIntent)
...
}
NotificationBroadcastReceiver:
class NotificationBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Timber.d("NotificationBroadcastReceiver onReceive")
Toast.makeText(context, "Notification dismissed", Toast.LENGTH_LONG).show()
// Send a request to the server.
}
}
AndroidManifest:
<uses-permission android:name="com.uremont.NOTIFICATION_PERMISSION" />
<receiver
android:name=".receiver.NotificationBroadcastReceiver"
android:exported="true"
android:permission="NOTIFICATION_PERMISSION"
>
<intent-filter>
<action android:name="notification_cancelled" />
</intent-filter>
</receiver>
仅在应用程序打开时有效。但是当应用程序在后台或被杀死时,它不会对滑动做出反应。可能我们不应该使用BroadcastReceiver,例如,使用PendingIntent.getService 或PendingIntent.getForegroundService。
我们可以向服务器发送请求吗?
【问题讨论】:
标签: android firebase-cloud-messaging android-pendingintent