I need to use non-collapsible notification by Firebase. For that I am using data-message like this:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
This message is interpreted in the onMessageReceived() method.
I still want to display this data-message in the tray just like notification-messages are displayed by the system automatically.
How to I achieve this? I cannot find documentation on this.
Thanks!
You can retrieve the values from your data payload in onMessageReceived() by calling RemoteMessage.getData(), then .get("<KEY_HERE>"). Like so:
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "onMessageReceived()");
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String dataTitle = remoteMessage.getData().get("data_title");
String dataBody = remoteMessage.getData().get("data_body");
sendNotification(dataTitle, dataBody);
}
You have to then build and display the Notification yourself. Like so:
private void sendNotification(String title, String body) {
Notification notif = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notif);
}
Related
I need to use non-collapsible notification by Firebase. For that I am using data-message like this:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
This message is interpreted in the onMessageReceived() method.
I still want to display this data-message in the tray just like notification-messages are displayed by the system automatically.
How to I achieve this? I cannot find documentation on this.
Thanks!
You can retrieve the values from your data payload in onMessageReceived() by calling RemoteMessage.getData(), then .get("<KEY_HERE>"). Like so:
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "onMessageReceived()");
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String dataTitle = remoteMessage.getData().get("data_title");
String dataBody = remoteMessage.getData().get("data_body");
sendNotification(dataTitle, dataBody);
}
You have to then build and display the Notification yourself. Like so:
private void sendNotification(String title, String body) {
Notification notif = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notif);
}
My app is receiving the notification correctly but is failing to show a notification pop up with the received info (If the app is opened).
N.B.: In case if the app is in the background, the notifications are displayed without any issue.
My Code:
I receive the notification in this method:
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.d(TAG, "From: " + remoteMessage.getFrom());
if(remoteMessage!=null)
{
String id = null;
String title = null;
String body = null;
String launchPage = null;
if(remoteMessage.getNotification()!=null)
{
title = remoteMessage.getNotification().getTitle();
body = remoteMessage.getNotification().getBody();
}
if(remoteMessage.getMessageId()!=null)
{
id = remoteMessage.getMessageId();
}
Log.i(TAG, "id: " + id);
Log.i(TAG, "title: "+ title);
Log.i(TAG, "body: " + body);
int notif_id = 0;
sendNotification(notif_id, title, body, launchPage);
}
}
then it calls this one (which is supposed to show the notification as i understand):
private void sendNotification(int id, String title, String messageBody, String launchPage)
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle("OMR - "+title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setChannelId(CHANNEL_ID);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel(notificationManager, CHANNEL_ID);
}
Toast.makeText(this, "Received a notif...", Toast.LENGTH_SHORT).show();
//this line is not showing a notification
notificationManager.notify(id, notificationBuilder.build());
}
Firebase notification
{
"data": {
"message": "data payload only used to force using OnMessageReceived() if in BACKGROUND",
"notif_id": 1
},
"to" : "e04OAVaRw30:APA91bGyv5_tt4IWRkurjlqkqNlCxTBV8oRne18tQ5puniHPItOMgg11kdt56t5jfZnasb4Ms-tH9xUgWQhHy2eM487llRtlM9_V_PoWJI9KSr6XgCaysiDyS",
"notification": {
"title": "Notification",
"body": "This is Notification 2",
"sound":"default"
}
}
Result
the notification is built correctly
sound played correctly
notif put in system tray
BUT no notification popup appears (i have to show a
custom dialog for that)
My Problem lies in this specific line
notificationManager.notify(id, notificationBuilder.build());
which is failing to show the notification
Update
i have read more about Android notifications in
https://developer.android.com/guide/topics/ui/notifiers/notifications
and found out that notifications only show in the notification drawer without popping up (as Heads-up notifications).
and according to this question, i can force the notifications to show as Heads-up notifications if i added a high priority to them. Unfortunately this is not working either.
This image explains it all if you are using FCM.
Well, in my case some of the data I'm passing into the message body is null in the onReceived.
Fixed that and my notification popup was showing again
Change
val notificationManager = packageContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
to
val notificationManager = NotificationManagerCompat.from(packageContext.applicationContext)
helps to me
I am trying to display a notification when the fcm message received and the APP is in the background. I tried different flavors of notifications but not luck. The notification won't show
Here is the code
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(GlobalVar.TAG, "From: " + remoteMessage.getFrom());
super.onMessageReceived(remoteMessage);
String channelId = getString(R.string.notification_channel_id);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
I know this is getting called because I get the log.
If the app is in the background then FCM displays notifications. It is the above code that is not displaying it when app is in foreground
Any suggestions?
PS: I created the channel in the Application class
I don't get errors in the log cat. I am also setting all the notifications settings as per code below. Please note my device receive and display notifications already from FCM when it is in background. But when it is in foreground and "I" handle the display of notification then it does not work
Hopefully your server is sending you notification in data key.
Here as I saw your code, You are getting notification data using remoteMessage.getNotification()
Now you have to make changes in your server side script that they send in data key as follow (You can test temporary before changing server code):
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"data" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
and after that you can receive like this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
}
To know more about it:
Hope you will get help in this. Do let me know if you get any problem.
If you're not using your own server, then you can't achieve this. You need to use your own server to modify the JSON format from this:
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
to:
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"data" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
when your server will modify "notification" tag with "data" then only you can recieve notification in background.
I am sending some push notifications to android from AWS,
the notification process is working registering the device, and I indeed get the test notifications, but only showing on the log, not on notification bar on top of the screen like any other notification would...
public void onMessageReceived(RemoteMessage remoteMessage) {
// ...
// TODO(developer): Handle FCM messages here.
Log.d("mako", "A From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d("mako", "B Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long-running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
// scheduleJob();
} else {
// Handle message within 10 seconds
// handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d("mako", "C Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// 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.
}
So, I send a test notification:
{
"GCM": "{ \"data\": { \"message\": \"test message\" } }"
}
And I can see in my console log the message test:
10-05 14:57:08.827 23062-23296/com.sb.comm D/mako: B Message data payload: {message=test message}
But is not showing on the little pop-up, What is missing to show the actual push notification on the screen?
Cheers
You have to Generate Notification on your device like this
public void onMessageReceived(RemoteMessage remoteMessage) {
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("App Name")
.setBadgeIconType(R.drawable.ic_notification)
.setLargeIcon(BitmapFactory.decodeResource(
getResources(),R.drawable.ic_notification))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(remoteMessage.getData().get("body"));
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(141, notificationBuilder.build());
}
Here Notification Builder will get data from your server notification payload and generate a notification on device.
please add these lines of code to show notification on notification bar.
Intent intent = new Intent(this, YourActivity.class);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this, "my_chanel_id");
notificationBuilder.setSmallIcon(R.drawable.ic_launcher_app);
notificationBuilder.setContentTitle("Titlee");
notificationBuilder.setContentText("anyText");
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(uri);
notificationBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";// The id of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel("mychanelId",
"hyperlocal", importance);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(message_id, notificationBuilder.build());
Turns out it was to do with the formatting of the body, it is not as suggested by >>> SNS "JSON message generator"
the body should be in this format:
{
"GCM": "{ \"notification\": { \"text\": \"test message\" } }"
}
I am facing issue while using push notification Firebase,
Issue :
App Icon appears white on a marshmallow and above, so I created the white and transparent set of icons, now push notification icons to appear as I needed but only when the app is on the foreground when a user gets a notification and app is closed the icon appears white itself.
My Manifest
<application
android:name="com.xxxx"
android:allowTaskReparenting="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_xxxx"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#style/AppTheme">
Notification Code : when I get push notification
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.xxxxxx)
.setColor(getResources().getColor(R.color.accent))
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
} else {
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count, notificationBuilder.build());
on Message Recieve Code
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
//Calling method to generate notification
//remoteMessage.getNotification().getBody()
sendNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
There are two types of notification there.
1.) using default params
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Server Side Code:
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
This type of implementation only works when the app is open or in background. You will notified message received ( blank notification will appear as you said) but you won't get any data from it.
2.) using map
Map data = remoteMessage.getData();
Server Side Code:
{
"message":{
"token" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "This is an FCM notification message!",
"title" : "FCM Message",
}
}
}
This will receive even after the app closed. It won't produce the blank white notification.
IF its issue with notification icon as white. Try adding this code in manifest
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/app_icon" />