I'm using firebase message service to get notification to my android app but the service not called but once! how to handle it to make it called whenever I got message? here is my code:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String user_id = "0";
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
user_id = remoteMessage.getData().get("from_user");
}
String click_action = remoteMessage.getNotification().getClickAction();
Log.d(TAG, "Message data payload: " + click_action);
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, click_action);
}
private void sendNotification(String messageBody, String messageTitle, String user_id, String click_action) {
Intent intent = new Intent(click_action);
intent.putExtra("user_id", user_id);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
and there is my payload:
const payload = {
notification: {
title: "New Friend Request",
body: `${userName} has sent you a Friend Request`,
icon: "default",
click_action: "com.example.alaa.lapitchatapp.Target_Notification"
},
data:{
from_user: from_user_id
}
};
This is the service in the Mainfest:
<service android:name=".FirebaseMessagingService">
<intent-filter>
<action
android:name=
"com.google.firebase.MESSAGING_EVENT"
/>
</intent-filter>
</service>
The way you are sending notification your
onMessageReceived()
will not be called when your app is in background or killed to solve this issue remove notification field while sending notification and send only data like this{ data:{ from_user: from_user_id // you can add more field if you want } };
include
"priority": "high"
filed in your notification request so that you will get the notification asap for more detail check this answerAfter way too much digging, I've realised that
The notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of my launcher Activity.
So I was supposed to handle the extras from the activity in which I was sending the notification to. The answer was in here
Therefore, there was no need to write any code inside the onMessageReceived().
Thanks a bunch for you All. Really appreciate it