Firebase Push Notification Doesn't Replace the Exisiting Notification - android

I'm creating a chat application which send push notifications using firebase
as my chatApp goes in background and send push notifications in row it generate new notification everytime as i have created a unique notification id for it.
I want to group to notification or update the existing one.
Image that Doesnt Group Firebase Push Notifications
Here is my Code of Firebase Messaging Service
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public int no_of_messages = 0,i=0;
private int notify_id= 12121; // this was my actual code
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotification(remoteMessage, remoteMessage.getData().get("message"));
no_of_messages++;
}
private void showNotification(RemoteMessage remoteMessage, String message) {
Intent i = new Intent(remoteMessage.getNotification().getClickAction());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Uri notification = Uri.parse("android.resource://"
+ this.getPackageName() + "/" + R.raw.coin);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
PendingIntent pendingIntent;
pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
if (no_of_messages == 0) {
builder.setAutoCancel(true)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setSmallIcon(R.drawable.auto)
.setSound(notification)
.setNumber(no_of_messages)
.setContentIntent(pendingIntent);
} else {
builder.setContentTitle(no_of_messages+"New Messages")
.setNumber(no_of_messages)
.setContentText(remoteMessage.getNotification().getTitle());
}
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(notify_id, builder.build());
}
}
PHP script
function for sending to FCM
function send_to_fcm($token,$title,$message,$click_action){
$body = array("to"=>$token."",
"notification" => array(
"title" => $title ,
"body"=> $message,
"click_action"=>$click_action,
'vibrate' => 1,
'sound' => "coin",
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
)
);
echo json_encode($body);
$header = array("Authorization:key=".FCM_SERVER_KEY,"Content-type:application/json");
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, FCM_PATH);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
$buffer = curl_exec($ch);
curl_close($ch);
//echo $buffer;
}

For update existing notification notify_id must be same as older one.
if notify_id will be changed it will generate new notification will not update existing one.
I am using below code for check message contain data payload or notification payload (notification payload contains notification from PHP)
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
title = remoteMessage.getData().get("title");
message = remoteMessage.getData().get("body");
image = remoteMessage.getData().get("icon");
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
title = remoteMessage.getNotification().getTitle();
message = remoteMessage.getNotification().getBody();
image = remoteMessage.getData().get("image");
}

In order to replace the notify_id must be same as previous. Use some constant value.

[ FIX ]
So there was a problem in PHP script
I Used "notification" as parameter for sending Notification
i Changed it to "data" which solved my problem
here is PHP Script
$body = array("to"=>$token."",
"data" => array(
"title" => $title ,
"body"=> $message,
"click_action"=>$click_action,
'vibrate' => 1,
'sound' => "coin",
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
)
);
and
MyFirebaseMessangingClass
Intent i = new Intent(remoteMessage.getData().get("click_action"));
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Uri notification = Uri.parse("android.resource://"
+ this.getPackageName() + "/" + R.raw.coin);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
PendingIntent pendingIntent;
pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
if (no_of_messages == 0) {
builder.setAutoCancel(true)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("body"))
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(notification)
.setNumber(no_of_messages)
.setContentIntent(pendingIntent);
no_of_messages++;
} else {
builder.setContentTitle("Eaziche | "+no_of_messages+" New Messages")
.setNumber(no_of_messages)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(notification)
.setNumber(no_of_messages)
.setContentIntent(pendingIntent)
.setContentText(remoteMessage.getData().get("title"));
}
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(notify_id, builder.build()); // notify_id = 12121

Related

onMessageReceived method in FirebaseMessagingService is not called

I'm sending notification using a firebase cloud function. When I'm sending the payload with notification key, notification sends but method not invoked. But with data key, nothing happened.
Here is my code for FirebaseMessagingService
#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"));
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());
}
}
private void sendNotification(String title, String messageBody){
String channelId = getString(R.string.default_notification_channel_id);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(messageBody)
.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_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 , notificationBuilder.build());
}
Here is my firebase cloud function
exports.sendNotification = functions.database
.ref("/deals/{userId}/{dealId}")
.onCreate((data, context) => {
const dataValue = data.val();
const topic = context.params.userId;
const payload = {
data: {
title: "New deal created",
body: dataValue.user.name + " added a new deal."
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
return admin
.messaging()
.send(payload)
.then(response => {
// Response is a message ID string.
console.log("Successfully sent message:", response);
})
.catch(error => {
console.log("Error sending message:", error);
});
});
Also I set up a debugpoint on onMessageReceived() but it did not get fired up.
I figured out the problem. The issue is after doing some changes and building the android project we need to subscribe to topic again.
When your app is in background , firebase will not trigger
OnMessageReceived instead it will show a notification alert
+
make sure you have subscribed the correct topic
+
make sure play services are updated on your device.

FCM never delivers when app is in background

I have integrated FCM in my app. Whenever app is in background, no fcm message is received. I have tried both notification type and data type messages. Even notification messages are not displayed in notification tray. They are just lost!
Please help me out where I am going wrong. I have followed everything as per documentation and have been researching on this for a whole week.
My Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application ....>
<service
android:name=".MyFirebaseMessagingService"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
My Firebase messaging service:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
SharedPreferences sharedPref;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
}
#Override
public void onNewToken(String token) {
sendRegistrationToServer(token);
}
private void sendRegistrationToServer(String token) {
//Sending handled here
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody) {
Intent intent = new Intent(this, UserHomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("title", title);
intent.putExtra("message", messageBody);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 273, intent,
PendingIntent.FLAG_ONE_SHOT);
//String channelId = getString(R.string.default_notification_channel_id);
String channelId = "Sandeep123";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher_foreground_new)
.setColorized(true)
.setColor(Color.BLUE)
.setContentText(messageBody)
.setAutoCancel(true)
.setVisibility(VISIBILITY_PUBLIC)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
getString(R.string.channel_name),
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(createID(), notificationBuilder.build());
}
public int createID() {
Date now = new Date();
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(now));
return id;
}
}
I have added both my debug and release SHA-1 in firebase console. I dont know where else i can be going wrong. It works on all devices when app is active. But it does not work at all when app is in background.
*------------Update - server side code
function sendGcmNotification($amountAdded, $tok,$des){
define( 'API_ACCESS_KEY', '***' );
$title = "Rs.".$amountAdded." added as credit";
$notificationMsg = "***";
//$token = array();
//$token[] = $tok;
$msg =
[
'message' => $notificationMsg,
'title' => $title
];
$android = ["priority"=>"high"];
$fields =
[
'to' => $tok,
'data' => $msg,
'time_to_live' => 900,
'priority' => 10,
'android' => $android
];
$headers =
[
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
}
The Log cat Log is as follows:
2019-01-24 11:14:08.310 1541-1578/? W/ActivityManager: Background start not allowed: service Intent { act=com.google.firebase.MESSAGING_EVENT pkg=in.dailydelivery.dailydelivery cmp=in.dailydelivery.dailydelivery/.MyFirebaseMessagingService (has extras) } to in.dailydelivery.dailydelivery/.MyFirebaseMessagingService from pid=26445 uid=10210 pkg=in.dailydelivery.dailydelivery 2019-01-24 11:14:08.311 26445-26445/?
E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found
Please help me out.
Sandeep.
For FCM to deliver the message to app in foreground/background to create notification on notification bar the message format being send from app server should match the following format, please note Notification Message won't receive any callback when app is background, only Data message will receive
Notification Message format:
{
"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"
}
}
}
Refer below link for more details
https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message
For fcm to deliver the push notification when device is locked or in background, the message from app server should have the following tags
{
....
"android": {"priority":"high"},
"priority": 10,
....
}
Refer below for more details
https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
Handling Messages: Receive messages in an Android app
You need to declare the service in the application tag of your Manifest.
see this sample code.
To know more, please check this guide.

Android Receive Silent Firebase Notifications

hello i have android application and i used Firebase notification and its working good ,, now i need to receive silent push without alert or anything ,,, i tried some idea and its working when app is running but when app in background or terminated its not working ! if anyone have idea to sole this issue please tell me :) this is my code
public class MyFirebaseMessagingService extends FirebaseMessagingService {
Boolean isSilent;
String Silent = "";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
Bundle bundle = new Bundle();
for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
bundle.putString(entry.getKey(), entry.getValue());
Log.d(entry.getKey(), entry.getValue());
}
// remoteMessage.getData().get("screen_id")
if (remoteMessage.getData().size() > 0) {
sendNotificationData(bundle.getString("data_title"), bundle.getString("data_body"), bundle.getString("screen_id"));
} else if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification(), bundle.getString("screen_id"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void sendNotification(RemoteMessage.Notification notificationR, String screenId) {
NotificationManager nManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent intentNotification = new Intent(this, MainActivity.class);
intentNotification.putExtra("screen_id", screenId);
Log.v("sendNotification ", " >>>>>####>>>>>>>> " + screenId);
// finish previous activity
if (!Silent.equals("yes")) {
intentNotification.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 50, intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this.getApplicationContext())
.setContentTitle(notificationR.getTitle())
.setContentText(notificationR.getBody())
.setSmallIcon(getNotificationIcon())
.setLargeIcon(icon(getApplicationContext()))
.setLights(Color.LTGRAY, 1000, 1000)
.setAutoCancel(true)
.setTicker(notificationR.getTitle())
.setContentIntent(pendingIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = notificationBuilder.build();
// '|' Binary OR Operator copies a bit if it exists in either operand. to ensure no conflict on the flags
notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;
nManager.notify((int) SystemClock.currentThreadTimeMillis(), notification);
}
}
private void sendNotificationData(String dataTitle, String dataBody, String screenId) {
NotificationManager nManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent intentNotification = new Intent(this, MainActivity.class);
intentNotification.putExtra("screen_id", screenId);
if (!Silent.equals("yes")) {
intentNotification.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 50, intentNotification, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this.getApplicationContext())
.setContentTitle(dataTitle)
.setContentText(dataBody)
.setSmallIcon(getNotificationIcon())
.setLargeIcon(icon(getApplicationContext()))
.setLights(Color.LTGRAY, 1000, 1000)
.setAutoCancel(true)
.setTicker(dataTitle)
.setContentIntent(pendingIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = notificationBuilder.build();
// '|' Binary OR Operator copies a bit if it exists in either operand. to ensure no conflict on the flags
notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;
nManager.notify((int) SystemClock.currentThreadTimeMillis(), notification);
}
#Override
public boolean zzE(Intent intent) {
isSilent = intent.hasExtra("silent");
if (isSilent) {
Silent = "yes";
}
return super.zzE(intent);
}
when app is running this code is working but at background or terminated its not working !!
When your app is in Background firbase notification message received on 'System tray' that's why FirebaseMessagingService.onMessageReceived not called.
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
Try to sent data payload that will call onMessageReceived. and your code will
work
For data message....
Get firebase token from FirebaseInstanceIdService and sent it to app server.
Google have very good documentation to sent it Here
You can sent it using php also.
Then on onMessageReceived
if (remoteMessage.getData().size() > 0) {
String title = remoteMessage.getData().get("title");
String body = remoteMessage.getData().get("body");
String screen = remoteMessage.getData().get("screen");
sendNotification(title, body, screen );}
For Server side php implementation
<?php
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$headers = array(
'Authorization:key='YOUR_SERVER_KEY,
'Content-Type:application/json'
);
$reg_id_array = array
(
'token1',
'token2'
)
$mesg = array
(
'title'=>$_POST['title'],
'body'=> $_POST['message'],
'url'=>$_POST['Screen'],
);
$fields = array("registration_ids"=>$reg_id_array, 'data'=>$mesg);
$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$Qresult = curl_exec($curl_session);
$httpcode = curl_getinfo($curl_session , CURLINFO_HTTP_CODE);
curl_close($curl_session);
if ($httpcode==200) {
echo "Success";
}
?>
Sorry bad English
A Notification contains 2 thigs:
the notification itself and
extra data.
You seem to have data in your code because of values such as screen_id, data_title``etc. It actually looks you are reading everything from thedata` part, I will leave the docs here just in case. In the first table in that page explains where each notification is handled.
Since you use data, all notifications will be manged in onMessageReceived, so the only think I can think of is you terminated the app from Android Studio (through the Stop button).
Doing so, the App terminates, and also does background Firebase instance. All processes exit. So try closing it from the mobile, and report if it worked.
Good luck.

Devices not receiving notification even though it is successfully sent in the logs

I am making a simple messaging app using firebase cloud messaging service but and I am using cloud functions to handle the notifications, however whenever I test it it always says successful in the logs but the devices receive nothing
Here is the cloud function used :
exports.sendNotifications = functions.database.ref('/meesages/{messageId}').onCreate(event => {
var eventSnapshot = event.data;
var str1 = "Sender : ";
var str = str1.concat(eventSnapshot.child("messageOwner").val());
console.log(str);
var topic = "Messaging";
var payload = {
notification: {
Message: eventSnapshot.child("messageText").val(),
Sender: eventSnapshot.child("messageOwner").val()
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic,payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
Here is the class responsible for handling the notifications part on the android device :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
showNotification(remoteMessage.getData().get("Sender"), remoteMessage.getData().get("Message"));
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
#Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
private void showNotification(String Message, String Sender) {
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_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("New message : " + Message)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("By : " + Sender)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
and yes I made sure to add the topic subscription in the mainactivity class
FirebaseMessaging.getInstance().subscribeToTopic("Messaging");
so what is exactly wrong here ??
The code in onMessageReceived() expects the message to have a data payload. This is explained in the documentation, which includes three tabs, showing notification, data, and combined payloads. Change notification to data:
var payload = {
data: {
Message: eventSnapshot.child("messageText").val(),
Sender: eventSnapshot.child("messageOwner").val()
}
};

Firebase (FCM): open activity and pass data on notification click. android

There should be clear implementation of how to work with Firebase notification and data. I read many answers but can't seem to make it work. here are my steps:
1.) I am passing notification and data to android in PHP and it seems to be fine:
$msg = array
(
"body" => $body,
"title" => $title,
"sound" => "mySound"
);
$data = array
(
"user_id" => $res_id,
"date" => $date,
"hal_id" => $hal_id,
"M_view" => $M_view
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg,
'data' => $data
);
$headers = array
(
'Authorization: key='.API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
2.) when notification and data is received in Android it shows notification. When I click on this notification it opens app. But I can not figure out the way to handle the data when the app is opened. There are couple differences when app is in foreground and backround. The code that I have now is the following:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String user_id = "0";
String date = "0";
String cal_id = "0";
String M_view = "0";
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
user_id = remoteMessage.getData().get("user_id");
date = remoteMessage.getData().get("date");
hal_id = remoteMessage.getData().get("hal_id");
M_view = remoteMessage.getData().get("M_view");
}
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody(), user_id, date, hal_id, M_view);
}
private void sendNotification(String messageBody, String user_id, String date, String hal_id, String M_view) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("fcm_notification", "Y");
intent.putExtra("user_id", user_id);
intent.putExtra("date", date);
intent.putExtra("hal_id", hal_id);
intent.putExtra("M_view", M_view);
int uniqueInt = (int) (System.currentTimeMillis() & 0xff);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), uniqueInt, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
3.) When I use the code above and when I click on notification all it does it opens the app if in background. If app in foreground then on notification click it simply dismisses notification. However, I want to receive data and open specific Activity in both scenarios (background and foreground). I have in MainActivity the following code, but I am not able to get data. fcm_notification, date, hal_id returns null.
public class MainActivity extends Activity {
UserFunctions userFunctions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Intent intent_o = getIntent();
}
#Override
protected void onResume() {
super.onResume();
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
Intent intent_o = getIntent();
String fcm_notification = intent_o.getStringExtra("fcm_notification") ;
String user_id = intent_o.getStringExtra("user_id");
String date = intent_o.getStringExtra("date");
String hal_id = intent_o.getStringExtra("hal_id");
String M_view = intent_o.getStringExtra("M_view");
Intent intent = new Intent(this, JobList.class);
// THIS RETURNS NULL, user_id = null
System.out.print("FCM" + user_id);
startActivity(intent);
finish();
}else{
// user is not logged in show login screen
Intent login = new Intent(this, LoginActivity.class);
startActivity(login);
// Closing dashboard screen
finish();
}
}}
IF anyone can direct or advice how can I retrieve data in MainActivity.java from Firebase in either scenario (foreground or background) that would be fantastic.
So first off, I'll put in the detail mentioned in the Handling Messages docs.
In the summary under the Both row, it shows that when the app is on foreground, the payload will be handled in your onMessageReceived().
In order to open the activity from onMessageReceived(), you should check if the data you need is in the payload, if it does, call your specific activity then pass all the other details you need via intent.
Now if the app is in background, it is mentioned in the docs that the notification is received by the Android system tray and that the data payload can be retrieved from the extras of the intent.
Just adding in the details from my answer here which pretty much just gives the docs statement and a link to a sample:
Handle notification messages in a backgrounded app
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
I think this answer by #ArthurThompson explains it very well:
When you send a notification message with a data payload (notification and data) and the app is in the background you can retrieve the data from the extras of the intent that is launched as a result of the user tapping on the notification.
From the FCM sample which launches the MainActivity when the notification is tapped:
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
After trying all the answers and blogs came up with solution. if anyone needs please use this video as reference
https://www.youtube.com/watch?v=hi8IPLNq59o
IN ADDITION to the video to add intents do in MyFirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String user_id = "0";
String date = "0";
String hal_id = "0";
String M_view = "0";
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
user_id = remoteMessage.getData().get("user_id");
date = remoteMessage.getData().get("date");
cal_id = remoteMessage.getData().get("hal_id");
M_view = remoteMessage.getData().get("M_view");
}
String click_action = remoteMessage.getNotification().getClickAction();
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, date, hal_id, M_view, click_action);
}
private void sendNotification(String messageBody, String messageTitle, String user_id, String date, String hal_id, String M_view, String click_action) {
Intent intent = new Intent(click_action);
intent.putExtra("user_id", user_id);
intent.putExtra("date", date);
intent.putExtra("hal_id", hal_id);
intent.putExtra("M_view", M_view);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}}
and in new NotificationReceive activity in onCreate or onResume add this
notification_Y_N = (TextView) findViewById(R.id.notification_Y_N);
user_id_text = (TextView) findViewById(R.id.user_id_text);
Intent intent_o = getIntent();
String user_id = intent_o.getStringExtra("user_id");
String date = intent_o.getStringExtra("date");
String hal_id = intent_o.getStringExtra("hal_id");
String M_view = intent_o.getStringExtra("M_view");
notification_Y_N.setText(date);
user_id_text.setText(hal_id);
To invoke the onMessageReceived() method you will need to use another method to send notifications (like creating a Web API to send notifications). Then using it,
remove the notification payload from your FCM messages in order to have the data payload delivered to the onMessageReceived() method.
When your app is in the background, data payload is delivered to the onMessageReceived method only if there is no notification payload.
In case both payloads exist then system automatically handles the
notification part (system tray) and your app gets the data payload in
the extras of the intent of launcher Activity (after the user tap on
the notification).
For more info please refer to the following links:
Why is this happening? How to? How to handle push notifications?
Original answer by kws. Give him an upvote.
You don't need to implement sendNotification and onMessageReceived yourself.
When sending:
$data = array
(
"user_id" => $res_id
//whatever fields you want to include
);
$msg = array
(
"body" => $body,
"title" => $title,
"data" => $data
// more fields
);
android side (on your MainACtivity:
private void handleIntent(Intent intent) {
String user_id= intent.getStringExtra("user_id");
if(user_id!= null)
Log.d(TAG, user_id);
}
and of course:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handleIntent(getIntent());
}
whatever fields you put in data will be sent to your intent extra.
firstly, if you have data object and notification object in response . then ask the backend developer to remove notification object.
i hope my own class help .
public class MyFirebaseService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Log.d(TAG, "Message data payload:id " + remoteMessage.getData().get("mode_id"));
sendNotification(remoteMessage.getData().get("body"),
remoteMessage.getData().get("mode_id"), remoteMessage.getData().get("click_action"));
}
}
private void sendNotification(String messageBody, String id, String clickAction) {
Intent intent = new Intent(clickAction);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(intent);
intent.putExtra("id", id);
intent.putExtra("body", messageBody);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "111")
.setSmallIcon(R.drawable.venus_logo)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setLights(Color.GREEN, 3000, 3000);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel("111", "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(false);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert notificationManager != null;
notificationBuilder.setChannelId("111");
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(0, notificationBuilder.build());
} else {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
then add this to your manifest file .
<service
android:name=".data.services.MyFirebaseService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".ui.notifications.NotificationsDetailsActivity"
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:parentActivityName=".ui.home.HomeActivity"
android:taskAffinity="">
<intent-filter>
<action android:name="co.example.yourApp.ui.notifications_TARGET_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Firebase documentation has a great table to explain how it works
https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages
So if you have both data and notification and app is in a foreground when your receive it then you should create a notification by yourself in your service which extends FirebaseMessagingService (in onMessageReceived method)
In other case (app is in background) you can get your data from intent.extras of Activity, a notification will be created by a system to open main activity of the app

Categories

Resources