简体   繁体   中英

How to display a FCM Firebase notification sent with a server

Firebase offers two ways to seding a push notifications, using it's firebase console and using a server like in GCM was did before. Now we are translating our servers from GCM to Firebase, and we need to receive and show FCM notifications in the app.

I have the implementation of the official firebase website done, with the sample codes done, but I'm stuck on this part. When our server sends the push notification to Firebase, and firebase send's to my app, I'm receiving the notification in onMessageReceived method with a RemoteMessage parameter. I know that the message is inside RemoteMessage parameter, but I can't find any guide or sample code in the Firebase official documentation about how to deal with this to show the notification text on the android device notification bar.

As you can see on the official guides, it is not explained how to extract the message without problems from the RemoteMessage parameter. I know that you can search inside and find the String but I want to find a official guide about how to correctly and safely deal with this.

In the official documentation you have only this:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {    
    // 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());
        // Handle message within 10 seconds    
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // 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.
}

And this (which is not being called on the guide):

   private void sendNotification(String messageBody) {
        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 =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_main)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

您将从服务器接收一个json onMessageRecieve,然后您需要解析该json并从中获取值。一旦您解析了值,则可以使用sendNotification()方法发送它并显示您的要求

I have done something like this I am using addNotifcation() in place of sendNotification()

public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getData().get("body"));
    addNotification(remoteMessage.getData().get("body"), remoteMessage.getData().get("Nick"));
}

private void addNotification(String message, String title) {
    NotificationCompat.Builder builder =
            (NotificationCompat.Builder) new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher1)
                .setContentTitle(title)
                .setContentText(message);

    Intent notificationIntent = new Intent(this, app.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    // Add as notification
    NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0, builder.build());
}

Check below method, its working fine, I am getting json data from server in notification.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        AppLog.Log(TAG, "From: " + remoteMessage.getFrom());
        JSONObject json = null;

        if (remoteMessage.getData().size() > 0) {
            Log.v(TAG, "Message data " + remoteMessage.getData());

            json = new JSONObject(remoteMessage.getData());
            AppLog.Log(TAG, "Json object " + json);

        }

        if (json != null) {

            try {
                int icon  = R.mipmap.ic_launcher;
                int mNotificationId = 001;
                // MainDrawerActivity is the class which open on the click of notification in status bar
                Intent intent = new Intent(this, MainDrawerActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

                //FLAG_UPDATE_CURRENT is important
                PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);


                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                        this);
                Notification notification = mBuilder.setSmallIcon(icon).setTicker("your title").setWhen(0)
                        .setAutoCancel(true)
                        .setContentTitle("your title")
                        .setStyle(new NotificationCompat.BigTextStyle().bigText("message"))
                        .setContentIntent(pendingIntent)
                        .setContentText("message").build();

                NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(mNotificationId, notification);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM