I have tried to notify a notification with ringtone. I tried many code but its doesn't work .
i want to play a default ringtone when i send a notification .
notification is proper sent by me ..
but there is no sound in mobile .
My Code is
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCMPlugin";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// 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.
Log.d(TAG, "==> MyFirebaseMessagingService onMessageReceived");
if( remoteMessage.getNotification() != null){
Log.d(TAG, "\tNotification Title: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "\tNotification Message: " + remoteMessage.getNotification().getBody());
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("wasTapped", false);
for (String key : remoteMessage.getData().keySet()) {
Object value = remoteMessage.getData().get(key);
Log.d(TAG, "\tKey: " + key + " Value: " + value);
data.put(key, value);
}
Log.d(TAG, "\tNotification Data: " + data.toString());
FCMPlugin.sendPushPayload( data );
//sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody, Map<String, Object> data) {
Intent intent = new Intent(this, FCMPluginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
for (String key : data.keySet()) {
intent.putExtra(key, data.get(key).toString());
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getApplicationInfo().icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
If you are trying this on an emulator it would not work because, if I'm not mistaken, it does not have a default ringtone set at:
content://settings/system/ringtone
Have you tried testing
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getApplicationInfo().icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
On an actual device?
Check Whether your app is in the background. If the app is in the background the onMessageReceived function is not called hence no ringtone.
Related
I'm using Firebase cloudmessaging for my Android application notifications, So my issue is when I send a notification if the user dismisses the notification the next notification that I send if clicked is opening the the first notification that have been dismissed so even if I send the third notification and the user dismissed both first and second notifications, if clicked the third one it's going to open the first notification. I'm using Firebase cloud messaging with data and sending the (title, excerpt, image, link). in the notification bar everything is cool and correct but when clicked the link is changed and the webview is going to open the first notification.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage 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());
sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"),
Integer.parseInt(remoteMessage.getData().get("topic")), remoteMessage.getData().get("link"), remoteMessage.getData().get("imageUrl"), Integer.parseInt(remoteMessage.getData().get("id")));
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(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(),
0, " ", " ", 0);
}
}
// [END receive_message]
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob() {
// [START dispatch_job]
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
#TargetApi(Build.VERSION_CODES.O)
private void sendNotification(String messageTitle, String messageBody, int topic, String link, String imageUrl, int id) {
PendingIntent pendingIntent;
if (topic == 1){
Intent intent = new Intent(this, WebActivity.class);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", link);
intent.putExtra("title", messageTitle);
// Get the PendingIntent containing the entire back stack
pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
}else{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", link);
intent.putExtra("topic", topic);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
}
String channelId = getString(R.string.default_notification_channel_id);
InputStream in;
Bitmap myBitmap = null;
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
in = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(in);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setPriority(NotificationManager.IMPORTANCE_DEFAULT)
.setChannelId(channelId)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(myBitmap)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent))
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageTitle))
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(myBitmap))
.setGroupSummary(true)
.setGroup(String.valueOf(topic))
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = "The Channel";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
channel.setShowBadge(true);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup(String.valueOf(topic), "Articles"));
}
notificationManager.notify(id /* ID of notification */, notificationBuilder.build());
}
}
The expected result is if the user dismissed the first notification, And for the second notification if clicked, the webview opens the second information send from the notification.
So after alot of research I found out that I have to update my intent with PendingIntent.FLAG_UPDATE_CURRENT and changed the request code for the intent every time a new intent is created, that's the new code for any one had this issue in the future:
PendingIntent pendingIntent;
if (topic == 1){
Intent intent = new Intent(this, WebActivity.class);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
intent.putExtra("link", link);
intent.putExtra("title", messageTitle);
intent.setAction("actionstring" + System.currentTimeMillis());
// Get the PendingIntent containing the entire back stack
pendingIntent =
stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
}else{
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("link", link);
intent.putExtra("topic", topic);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
}
I'm struggling to get my FCM notifications to stack in the same way as for Whatsapp:
1) The latest message for a particular room is displayed, with an updated count of all unread messages.
2) Indicating separate groupings of point 1 for notifications for different rooms.
I have spent a few hours looking at various SO questions and this is the closest I've come to finding an answer. The issue is that I am using a data payload, not notification, and it doesn't seem like the "tag" property works for my data payload.
The current behavior is that only the latest notification shows, overriding the previous.
Here is the sendNotification() method in my FirebaseMessagingService
private void sendNotification(RemoteMessage remoteMessage) {
//Intent intent = new Intent(this, StudentChatActivity.class);
String clickAction = remoteMessage.getData().get("click_action");
Intent intent = new Intent(clickAction);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
String roomID = remoteMessage.getData().get("ROOMID");
String origin = remoteMessage.getData().get("ORIGIN");
String msgID = remoteMessage.getData().get("MSGID");
Log.d(TAG, "Message data payload, roomID: " + roomID);
intent.putExtra("ROOMID", roomID);
intent.putExtra("USERID", UserID);
intent.putExtra("USERNAME", UserName);
intent.putExtra("ORIGIN", origin);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.received_message);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.small_pickle)
.setContentTitle("FCM Message")
.setContentText(remoteMessage.getData().get("body"))
.setPriority(1)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
Log.d(TAG, "Noification ID: " + notify_no);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
I am newbie to android and learning new things,I am working on FCM push notification,I want to implement Big picture style push notifications,I have implemented it successfully,even i am getting notification along with message but i am facing a problem that in push notification image is not loading,can anyone help me to figure it out?
my service is as below.
MyFirebaseMessagingServiceTemp extends FirebaseMessagingService {
String store_id, img_url, msg;
private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
/*
There are two types of messages data messages and notification messages. Data messages are handled
here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
is in the foreground. When the app is in the background an automatically generated notification is displayed.
When the user taps on the notification they are returned to the app. Messages containing both notification
and data payloads are treated as notification messages. The Firebase console always sends notification
messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
*/
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());
JSONObject job = new JSONObject(remoteMessage.getData());
img_url = job.optString("img_url");
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
msg = remoteMessage.getNotification().getBody().toString();
}
//The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
//You can change as per the requirement.
//message will contain the Push Message
// String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
// String imageUri = remoteMessage.getData().get("img_url");
//If the key AnotherActivity has value as True then when the user taps on notification, in the app AnotherActivity will be opened.
//If the key AnotherActivity has value as False then when the user taps on notification, in the app MainActivity will be opened.
String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(img_url);
sendNotification(msg, bitmap);
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private void sendNotification(String messageBody, Bitmap image) {
Intent intent = new Intent(this, SlashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Log.d("====message body===>", messageBody);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(messageBody)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
/*
*To get a Bitmap image from the URL received
* */
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
How to add the fcm notification in inbox style when app is in background?
When i add the the below code i got inbox style when app is open
but if the app is background it showing seperate notification
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
Integer notify_no = 0;
Integer numMessages = 0;
DBHelper db = new DBHelper(this);
private final int notificationID = 237;
private static int value = 0;
// Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
//Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.newlogo);
// TODO(developer): Handle FCM messages here.
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());
/* Integer badge = Integer.parseInt(remoteMessage.getData().get("badge"));
Log.d("notificationNUmber",":"+badge);
setBadge(getApplicationContext(), badge);*/
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
Intent intent = new Intent();
intent.setAction("com.ksoft.propreka.CUSTOM_INTENT");
sendBroadcast(intent);
db.insertNotification(remoteMessage.getNotification().getBody(),remoteMessage.getData().get("room_id"));
//EventBus.getDefault().post(remoteMessage.getNotification().getBody());
//
try {
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getData().get("text"));
} else if (!remoteMessage.getData().isEmpty()) {
sendNotification(remoteMessage.getData().get("text"));
}
} catch (Exception e) {
Log.d("json error", e.toString());
}
//sendNotification(remoteMessage.getData().get("text"));
Log.d("test",":test notification");
//createpushnotification();
// 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.
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
public void sendNotification(String messageBody) {
Intent intent = new Intent(this,Main2Activity.class);
intent.putExtra("messages","messages");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("fcm_notification", "Y");
PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Propreka")
.setSmallIcon(R.mipmap.new_logo)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(Uri.parse("content://settings/system/notification_sound"))
.setVibrate(new long []{100,2000,500,2000})
.setContentIntent(pendingIntent);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(getResources().getString(R.string.app_name));
Integer msg_count = db.message_count();
Integer chat_count = db.chat_count();
inboxStyle.setSummaryText(" "+msg_count+" messages from "+chat_count+" chat");
ArrayList<ArrayList> Newchat = db.getNotifications();
for (ArrayList s : Newchat) {
inboxStyle.addLine(s.get(0).toString());
}
notificationBuilder.setStyle(inboxStyle);
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
/*Intent resultIntent = new Intent(getBaseContext(), Main2Activity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent piResult = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.new_logo)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(messageBody)
.setVibrate(new long []{0,100,10,100})
.setContentIntent(piResult);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
// String[] events = new String[6];
inboxStyle.setBigContentTitle(getResources().getString(R.string.app_name));
ArrayList<ArrayList> Newchat = db.getNotifications();
for (ArrayList s : Newchat) {
inboxStyle.addLine(s.get(0).toString());
}
mBuilder.setStyle(inboxStyle);
nManager.notify(getResources().getString(R.string.app_name),0 ,mBuilder.build());*/
}
public void createpushnotification()
{
Log.i("Start", "notification");
/* Invoking the default notification service */
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.mipmap.new_logo);
/* Increase notification number every time a new notification arrives */
mBuilder.setNumber(++numMessages);
/* Add Big View Specific Configuration */
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String[] events = new String[6];
events[0] = new String("This is first line....");
events[1] = new String("This is second line...");
events[2] = new String("This is third line...");
events[3] = new String("This is 4th line...");
events[4] = new String("This is 5th line...");
events[5] = new String("This is 6th line...");
// Sets a title for the Inbox style big view
inboxStyle.setBigContentTitle("Big Title Details:");
// Moves events into the big view
for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
mBuilder.setStyle(inboxStyle);
/* Creates an explicit intent for an Activity in your app */
Intent resultIntent = new Intent(this, Main2Activity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(Main2Activity.class);
/* Adds the Intent that starts the Activity to the top of the stack */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* notificationID allows you to update the notification later on. */
mNotificationManager.notify(notificationID, mBuilder.build());
}
}
how to add the inbox style?
Use data payload to send the notification data and show it the phone using this class.
For example:
With Notification payload
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon"
}
}
This data will show default notification to the phone by the firebase when the app is in background but the onMessageReceived method from FirebaseMessagingService will be called when app is in foreground.
With data payload
Everytime you send notification onMessageReceived method will be called. So you can build notification as you want.
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
For more detail head out to the the official documentation here.
There is two type of FCM messages.
Notification Message.
Data Messages.
FCM
Send data message, then it will come in your call method.
When application in background then, FCM not call the onMessageReceived method.
Instead of it display the default notification.
#Override
public void onMessageReceived(String from, Bundle data) {
dbhelper = DatabaseHelper.getInstance(this);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/teta")) {
if (message != null) {
final Alert alert = new Gson().fromJson(message, Alert.class);
Log.d(TAG, alert.getDesc() + " " + alert.getLink() + " " + alert.getTimeStamp() + " " + alert.getTitle());
dbhelper.addAlertsToDB(alert, DatabaseHelper.NEW);
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(AppPreferences.NEW_ALERT_RECIEVED));
boolean notifPref = sharedPreferences.getBoolean(AppPreferences.PREFERENCE_RECIEVE_NOTIFICATION, false);
if (notifPref) {
sendNotification("You Have A New Job Notification.", alert.getTitle());
Log.d(TAG, "Notifications turned " + notifPref + " ...User will be notified");
} else {
Log.d(TAG, "Notifications turned " + notifPref);
}
}
}
}
private void sendNotification(String message, String title) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_notifications_active_white_24dp)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(message)
.setSubText(title)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(notificationBuilder);
//Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String strRingtonePreference = sharedPreferences.getString(AppPreferences.PREFERENCE_SOUND, "");
Uri defaultSoundUri = Uri.parse(strRingtonePreference);
notificationBuilder.setSound(defaultSoundUri);
boolean vibrate = sharedPreferences.getBoolean(AppPreferences.PREFERENCE_VIBRATE, false);
if (vibrate) {
long[] pattern = {0, 200};
notificationBuilder.setVibrate(pattern);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
So my problem is to notify user about new messages without annoying him if the user has not already checked the old notification in status bar. I am not able to persist notification id and notification builder.
My server sends new alerts in a continuous stream of 5-10 alerts at once, but each item arrives separately asynchronously often one after other with a split second difference.
So it becomes very annoying for the user since he has not dismissed/viewed the old one.
I wish to update the content of previous notification in the status bar without notifying user....just like Gmail does.
First, add an ID to each notification. It can be a hashcode of the message title for example.
Second, each time you want to post a notification, use 'getActiveNotifications()' to get the array of active notifications. And if you find one with an equal ID, update it passing the existing ID.
And, if you don't want the sound, vibration and ticker to be played again, use the 'setOnlyAlertOnce(true)' option.