如何显示随服务器发送的FCM Firebase通知

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何显示随服务器发送的FCM Firebase通知相关的知识,希望对你有一定的参考价值。

Firebase提供了两种方式来发送推送通知,使用它的firebase控制台和使用GCM之前的服务器。现在我们正在将我们的服务器从GCM转换为Firebase,我们需要在应用程序中接收和显示FCM通知。

我完成了官方firebase网站的实现,完成了示例代码,但我仍然坚持这一部分。当我们的服务器向Firebase发送推送通知,并将firebase发送到我的应用程序时,我在onMessageReceived方法中使用RemoteMessage参数接收通知。我知道该消息是在RemoteMessage参数内,但我在Firebase官方文档中找不到任何指南或示例代码,关于如何处理此问题以在android设备通知栏上显示通知文本。

正如您在官方指南中看到的那样,没有解释如何从RemoteMessage参数中提取消息而没有问题。我知道你可以在里面搜索并找到String但我想找到一个关于如何正确和安全地处理这个问题的官方指南。

在官方文档中你只有这个:

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

这个(指南中没有调用):

   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()方法发送它并显示您需要的内容

另一答案

我做了类似这样的事情我使用addNotifcation()代替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());
}
另一答案

检查下面的方法,它工作正常,我从服务器通知中获取json数据。

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();
            }

        }
    }
}

以上是关于如何显示随服务器发送的FCM Firebase通知的主要内容,如果未能解决你的问题,请参考以下文章

php 简单的PHP FireBase(FCM)脚本,显示如何发送Android推送通知。请务必使用prope替换SERVER_API_ACCESS_KEY

客户端未收到主题服务器端的 FCM 通知

如何在 Xamarin.iOS 中使用 FCM(Firebase 云消息传递)发送 iOS 推送通知

如何跟踪FCM推送通知发送表单服务器端或Rest客户端? [重复]

使用 Java,而不是 FCM 控制台发送 Firebase 通知

使用 Firebase (FCM) 的丰富通知