如何显示与服务器一起发送的 FCM Firebase 通知

Posted

技术标签:

【中文标题】如何显示与服务器一起发送的 FCM Firebase 通知【英文标题】:How to display a FCM Firebase notification sent with a server 【发布时间】:2017-12-21 11:17:45 【问题描述】:

Firebase 提供了两种发送推送通知的方法,一种是使用它的 firebase 控制台,另一种是使用像以前在 GCM 中那样的服务器。现在我们正在将我们的服务器从 GCM 转换为 Firebase,我们需要在应用中接收和显示 FCM 通知。

我已经完成了官方 firebase 网站的实现,并完成了示例代码,但我被困在这部分。当我们的服务器将推送通知发送到 Firebase 并将 Firebase 发送到我的应用程序时,我会在 onMessageReceived 方法中收到带有 RemoteMessage 参数的通知。我知道消息在 RemoteMessage 参数中,但我在 Firebase 官方文档中找不到任何指南或示例代码,说明如何处理此问题以在 android 设备通知栏上显示通知文本。

正如您在官方指南中看到的那样,没有说明如何从 RemoteMessage 参数中毫无问题地提取消息。我知道您可以在里面搜索并找到字符串,但我想找到有关如何正确安全地处理此问题的官方指南。

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

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

【问题讨论】:

检查this 好帖子@Maddy 我会仔细阅读的 很高兴为您提供帮助:) 【参考方案1】:

我已经做了类似的事情,我正在使用 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());

【讨论】:

【参考方案2】:

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

【讨论】:

【参考方案3】:

检查下面的方法,它工作正常,我在通知中从服务器获取 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 通知的主要内容,如果未能解决你的问题,请参考以下文章

使用FCM从服务器发送推送通知

FCM 保持令牌同步

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

如何将 FCM 令牌发送到我的 php 服务器

如何不向不想接收推送的用户发送FCM?

如何将 apns-collapse-id 与 FCM 一起使用?