41

I have integrated Firebase Cloud Messaging with my application. When I sent a notification from the Firebase console, if the app is in background or not opened I receive successfully the notification, otherwise if the app is in foreground or opened, I did not receive it.

All suggestions are appreciated.

fdelafuente
  • 1,114
  • 1
  • 13
  • 24
Uma Achanta
  • 3,669
  • 4
  • 22
  • 49
  • 1
    Go through this link, this is the most simplest way to handle firebase notification by app instead of server when app is in foreground and background using postman. [Firebase Notifications in Background & Foreground in Android](https://wajahatkarim.com/2018/05/firebase-notifications-in-background--foreground-in-android/) – Abhinay Shrivastav Apr 07 '19 at 17:14

2 Answers2

98

When app is in foreground, notifications are not generated themselves. You need to write some additional code. When message is received onMessageReceived() method is called where you can generate the notification. Here is the code:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
        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);
        String channelId = "Default";
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }
        manager.notify(0, builder.build());
    }
}
Bugs Happen
  • 2,169
  • 4
  • 33
  • 59
Shivam Bhusri
  • 1,111
  • 9
  • 12
  • 2
    Any new notification will replace the previous one since you use 0 as an id – Louis CAD Nov 16 '17 at 22:20
  • 2
    Crashed my android phone's system UI. – Travis Whitten Dec 20 '18 at 20:49
  • TIP: You should also add a check for BUILD version > O. Else the notification will not appear in the emulator. My virtual device was NEXUS 5 (Which runs in Android O). I did not realize it at the first and went crazy for a few hours. – Rohit Singh Jan 15 '19 at 17:30
  • 1
    Notification behavior changes based on whether app is open or not! Any idea? – Jay Patel Dec 29 '19 at 12:56
  • @JayPatel in case of foreground, you have full control over notification so you can . easily create pending intent(if you want to open activity other than launcher activity on click of notification).But in case of background launcher activity opens on click of notification. – Shivam Bhusri Dec 31 '19 at 08:53
  • It's very puzzling to me that Firebase didn't provide a helper to turn the `RemoteMessage.Notification` object into a system notification more easily. It's literally what they do behind the scenes for background notifications, and I just wish we could reuse the code instead of repeating everything... – David Ferrand Sep 30 '22 at 11:08
5

FirebaseMessagingService never work when the app is in foreground. In this case if you want to receive the message from FCM then WakefulBroadcastReceiver will work for you

public class FirebaseDataReceiver extends WakefulBroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d("BroadcastReceiver::", "BroadcastReceiver");
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(intent.getExtras().getString("title"))
                    .setContentText(intent.getExtras().getString("message"));
            NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            manager.notify(0, builder.build());
        }
    }

Link firebase with GCM in play store and write the below code in manifest

<receiver
    android:name=".firebase.FirebaseDataReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</receiver>
Ramana V V K
  • 1,245
  • 15
  • 24