My notification work if the app is in the background but it doesn't work in the foreground
this is my MyFirebaseMessagingService class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String TAG = "MessagingService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
String uid = remoteMessage.getData().get("uid");
String click_action = remoteMessage.getNotification().getClickAction();
Log.d(TAG, "onMessageReceived: "+title + message + uid+" "+click_action);
Intent intent = new Intent(click_action);
if (click_action.equals("com.example.android.ProfileFriends")){
intent.putExtra("uid",uid);
}else if (click_action.equals("com.example.android.ChatActivity")){
}
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(message);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher_event);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
Please, how can i resolve this problem?
FCM has different behaviours for app status (foreground and background / killed). You should handle this by the payload you sent from server, according to your use case.
The msg sent from server has to be sent in either "notification" or "data" format, from dashboard or server side api. Note: From firebase dashobard you can only send "notification" body and not data. In such cases, FCM will directly display the notif without giving a callback to your app.
Server side Below are sample formats :
Notification Type Format Note : Android System will by default display the notification in the notification tray and you don't need to display it.
Data Format (For receiving callback in app, in foreground and background) Note : You have to handle callback and display notif on your own.
Android Client To handle the payload received in your Android receiver, checl the official guide here
Check the documentation here