How to add fcm notification? - android

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.

Related

Wrong notification when messages are unread on Android

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);
}

Notification doesn't notify

I am making MQTT client app using paho MQTT client dependency.
Implementing code in a Background Service. and everything works well except the Notification isn't working!
Service code snippet is here:
My Codes occurs inside the TimeDisplayTimerTask inner-class.
This code located at the callback function :
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
mIntent = new Intent(getApplicationContext(), MainActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, 0);
createNotificationChannel();
Toast.makeText(getApplicationContext(),"A message received : "+ new String(message.getPayload()),Toast.LENGTH_SHORT).show();
vibrator.vibrate(500);
myRingtone.play();
mBuilder .setContentTitle("Message received at : " + mTopic)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentText("Message : "+ new String(message.getPayload()));
mNotificationManager.notify(0, mBuilder.build());
}
And this code creates a notification channel (as Google developers guide mentioned to write):
Posted with help of this answer.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String chanel_id = "3000";
CharSequence name = "Mqtt message";
String description = "Message arrived";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
mNotificationManager = getSystemService(NotificationManager.class);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
mBuilder = new NotificationCompat.Builder(getApplicationContext(), chanel_id);
}
else
{
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext());
}
}
When it receives a message, A toast message appears holding the message.
But it doesn't push notification.
Checked Apps and Notifications, All notifications are allowed.
SOLVED :
the setter method .setSmallIcon must be called to successfully build a notification.
Which was not important to me.

Firebase Push Notification?

I am implementing firebase push notification in my app, the app is showing the push notification also. But my problem is - I may send different types of push notifications based on different topics.
Ex -
1. If I am sending a push notification on App Update, then on clicking that notification by the user, he should be redirected to PlayStore
If I am sending a push notification on New Contents, then on clicking that notification by the user, he should be redirected to App's MainActivity
If I am sending a push notification on New Contest, then on clicking that notification by the user, he should be redirected to App's ContestActivity
I implemented it using the below code in "MessageReceiver" class as --
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
showNotifications(title, message);
}
private void showNotifications(String title, String msg) {
Intent i = null;
if(title.equals("DoUp Now - Update")){
Uri uri = Uri.parse("https://play.google.com/store/apps/details?id=com.s2s.doupnow"); // missing 'http://' will cause crashed
i = new Intent(Intent.ACTION_VIEW, uri);
}
else if(title.equals("DoUp Now - New Content")){
i = new Intent(this, MainActivity.class);
}
else if(title.equals("DoUp Now - New Notification")){
i = new Intent(this, NotificationActivity.class);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE,
i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder, mBuilderOld;
final int NOTIFICATION_ID = 1;
final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
mNotifyManager.createNotificationChannel(notificationChannel);
mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilder.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.doupnowlogo)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
else
{
mBuilderOld = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilderOld.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.drawable.doupnowlogo)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_MAX);
mNotifyManager.notify(NOTIFICATION_ID, mBuilderOld.build());
}
}
But on clicking any notification by the user, he is always redirected to App's MainActivity only.
Can anyone guide me where i am missing.
If you are comparing title using api the you have to check the title using JSON object like this.
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
Make sure the title you get is equal as title you are comparing and add flags in intent.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

How to stack or group Firebase Cloud Messaging notifications in a Whatsapp style

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());
}

Play a default ringtone when i send a notification

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.

Categories

Resources