I'm new in push notifications and I have an issue, when app receive a notification and app is open the class "FCMIntentService extends FirebaseMessagingService" execute correctly, but when app is closed or in background don't execute this class. Why? and Which class process the notification?
Firebase cloud Messaging has two concept one is 'notification' and second is 'data'.
In foreground notifications are send to onMessageReceived() method properly, but in case of background, notifications are sent into system tray see the image.
Solution: Use data field to send notifications from the server.
Don't use notification object to send the notifications from the server
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{ // Don't use the notification
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
Use data field to send the notification from the server it will work in background and foreground as well.
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{ // Use the data object to send the notification
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
Related
I am developing an App where the user will receive a notification if any other user likes his picture.
I'm able to handle in-App notification and apply my conditions without any problem.
Unfortunately, I am not able to handle the background Notification.
This is what I did so far:
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (1 > 1) {
print('send it');
return true;
} else {
print('don\'t send it');
return false;
}
}
No matter what I do under _firebaseMessagingBackgroundHandler, notification will be shown anyways.
My handler is triggered and I can see the print in Console.
I believe there is another handle inside the FCM SDK that handles this notification, and the FirebaseMessaging.onBackgroundMessage is just an option.
Any thoughts? thank you!
The way you are trying to handle the background message is fine but there is more to know how the FCM really works.
First of all, Firebase Provide us two types of messaging
Notification Message
FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-
visible keys and an optional data payload of custom key-value pairs
Data Message
The client app is responsible for processing data messages. Data messages have
only custom key-value pairs with no reserved key names
Now for your scenario, you should send your message from Firebase as Data Message then you have control of it, otherwise, if you send the Notification Message from Firebase the notification will show automatically.
Here are example sample snippets of two different types of Firebase Message
Notification Message:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
Data Message
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
And finally, I recommend you take a look at the official documentation About FCM message.
I want to redirect to inbox screen after clicking on push notification on android and iOS
Case 1: App already opened on android. - Successfully Working
Push notification received. On Clicking on notification page redirected to inbox successfully.
NOTIFICATION: {"dealer": "SWRoa0ZhSkN4Y2hQNW1NeWtFdHFvSDNlcXIyNnc1TG5PS1hOZjJoMElHST0=", "finish": [Function finish], "foreground": false, "id": "-1073464079", "message": "hello", "messagetype": "RESPONSE", "subject": "ENQUIRY RESPONSE", "title": “Sample 1”, "userInteraction": true}
PushNotification.configure({
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
console.log('NOTIFICATION CLICK STATE : --->' + notification.userInteraction);
if(notification.userInteraction === true) {
NavigationService.navigate('Inbox');
}
},
popInitialNotification: true,
});
Case 2: App running in background or closed on android - Failed
Push notification received. On clicking on notification page redirection not working, only app get opened.
No notification data received
Case 3: On IOS in case of app opened or closed. - Failed
Push notification received. On clicking on notification page redirection not working, only app get opened.
No notification data received
I am using react-native-push-notification library for push notification.
https://github.com/zo0r/react-native-push-notification
Maybe it isn't good to promote other packages. However, I suggest looking into react-native-firebase will be good idea. It provides the feature to handle redirection even when the app is not on foreground.
I have a Flutter application using the firebase-messaging plugin for push notifications.
I register firebase like normal on the client, and I send the fcmToken to the server.
Notifications are created via a python server using aiofcm (which uses firebase's XMPP api). They're created like this:
message = aiofcm.Message(
device_token = t2,
notification = {
"title":notification_title,
"body":notification_body,
"sound":"default",
"tag":link
},
data = {
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
priority=aiofcm.PRIORITY_HIGH
)
await fcm.send_message(message)
On iOS, notifications pop-up at the top of the screen.
On Android, only the icon shows up in the notification tray - not any of the notification content. This is tested on a Pixel 3 and a OnePlus 6, both running Android P.
Ideally, I would like the notification to be "heads-up" style like this:
Before I was able to accomplish this using data messages and creating the notification programmatically in native android, however I would like to avoid that if possible since data messages don't get delivered on Android if the app is terminated.
To Get heads-up - Notification - Kindly set "alert: true"
Example :
notification = {
"title":notification_title,
"body":notification_body,
"sound":"default",
"alert" : true
"tag":link
},
For heads up notification you will need to use flutter_local_notifications Plugin. It is even recommended in FlutterFire official documentation for notification to show notification in foreground (background notification also supported ofcourse!) and it shows heads up notification by default.
You should check out the firebase.flutter.dev docs it shows how to do this easily with the help of flutter_local_notifiation
you can use background fetch and local notification package for background app running.
I am using the latest Bluemix Push Notification service. I'm using the MFPPush API to register the device (Android).
Here is my code snippet:
var success = function(message)
{
console.log("Success: " + message);
alert("Reg Device: " + message);
};
var failure = function(message)
{
console.log("Error: " + message);
alert("Error: " + message);
};
MFPPush.registerDevice({}, success, failure);
var notification = function(notification)
{
// notification is a JSON object.
alert(notification.message);
};
MFPPush.registerNotificationsCallback(notification);
The success message contains the following information:
Token:APA91bFtkSr59Zxlr52HU****Uij
UserId: ""
DeviceId: g5c6d98f-0867-3fd1-a353-15bcdef675a2
When I send the notification, my device receives the message.
The Swagger REST API shows that I can arbitrarily give some token, userId and deviceId:
{
"deviceId": "TestDeviceId",
"platform": "G",
"token": "************",
"userId": "Joe"
}
How do I get the "TestDeviceId", and how do I get the "token"? I don't see any API to get that information.
Note: You should probably just use the Client SDK to register as it handles all of this in the background--automatically assigning each device a unique ID. You shouldn't explore this unless you know what you're doing. There isn't a really a reason for trying to manually set the deviceID.
When you register a device for the Push Notifications service, you set these values in the body of the POST request. On a successful call, it will return these values in the response. I'll do a demo of this later in the post.
You can also retrieve a list of the device registrations for the Push Notifications service.
You can use that deviceId to retrieved detailed information about the device, send a specific push notification to that device, subscribe it to a tag and send push notifications to those devices, etc.
Swagger Documentation is here.
Regarding those values, you can put whatever you want in them when you register. Typically, these values would be set automatically by the Bluemix Mobile Android/iOS Client SDK when you do the register call. However, you could do this manually using the REST client.
For example:
Here, I'm registering a device:
It registered successfully:
This is what I get if I ask the Push Notifications service for information about my registered devices (for the "deviceId": "arandomdeviceid"):
The Android BMS Core Client SDK sets this deviceId using a unique UUID from the device and hashing it with MD5.
You can look in here more more information about that.
#anamica (a) Allow userId parameter to be passed along with the MFPPush registration like MFPPush.register({"userId": "AUniqueUserId"}, success, failure) (b) Add an additional parameter to the target "userIds" (array).
This enhancement has been done, you can give a try by updating the latest SDK.
I am trying to use the messages service in the Bluemix Services Push REST API to send a push notification to users who are subscribed to previously created tags. The problem is that when I send a notification to multiple tags, if a user is registered to more than one of those tags he is receiving the same notification multiple times.
The API says this:
tagNames (Array[string], optional): Send notification to the devices that have subscribed to any of these tags
So I understand that the user should only receive one notification, instead of what is happening.
My call looks like this:
{
"message": {
"alert": "Text notification",
},
"target": {
"tagNames": ["TAG1","TAG2","TAG3","TAG4","TAG5","TAG6","TAG7"]
},
"settings": {
"apns": {
"badge": 1,
"sound": "UILocalNotificationDefaultSoundName"
}
}
}
Confirmed with the Bluemix Push development team that this is indeed a defect in the service and you should only be receiving one notification in this instance. The team has created a defect for the issue and once it has been resolved and pushed to production I'll update this answer with whatever additional information or changes in usage come from the fix.
Thank you very much for bringing this to our attention