When an application receives push notification
from FCM
, it calls onMessageReceived
. (See 1, 2 or 3.)
When a user taps the notification, it launches the applications, then it sends a request to a server that the user has read the notification.
I want to know when a device received a push notification, but the user swiped it (or cleared all notifications). I want to send a request to the server that the user simply cancelled the notification.
I tried to send BroadcastReceiver
and show logs (see 4 or 5), but it works when the application was opened when the notification delivered. I suppose, that
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>
works only when the application is opened. But when the application is in background or killed, it doesn't react to swipe. Probably we shouldn't use BroadcastReceiver
, for instance, use PendingIntent.getService
or PendingIntent.getForegroundService
.
Can we send a request to the server?