如何使用 Firebase Cloud Messaging 在前台显示多个通知

Posted

技术标签:

【中文标题】如何使用 Firebase Cloud Messaging 在前台显示多个通知【英文标题】:how show more than one notification in foreground with Firebase Cloud Messaging 【发布时间】:2019-09-27 19:54:36 【问题描述】:

我在 android 中有一个应用程序接收来自 firebase 的通知,但是当它在前台时,新通知会替换之前的通知。我怎样才能显示全部? 这是我的课。

公共类 FirebaseNotifications 扩展 FirebaseMessagingService private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) 
    // [START_EXCLUDE]
    // There are two types of messages data messages and notification messages. Data messages
    // are handled
    // here in onMessageReceived whether the app is in the foreground or background. Data
    // messages are the type
    // traditionally used with GCM. Notification messages are only received here in
    // onMessageReceived when the app
    // is in the foreground. When the app is in the background an automatically generated
    // notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages
    // containing both notification
    // and data payloads are treated as notification messages. The Firebase console always
    // sends notification
    // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
    // [END_EXCLUDE]

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

        if (/* Check if data needs to be processed by long running job */ true) 
            // For long-running tasks (10 seconds or more) use WorkManager.
            scheduleJob();

         else 
            // Handle message within 10 seconds
            handleNow();

        
    

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) 
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        //message will contain the Push Message
        String message = remoteMessage.getNotification().getBody();
        //imageUri will contain URL of the image to be displayed with Notification
        String imageUri = remoteMessage.getNotification().getIcon();

        //To get a Bitmap image from the URL received

        sendNotification(message, imageUri);
    

    //The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
    //You can change as per the requirement.





@Override
public void onNewToken(String token) 
    Log.d(TAG, "Refreshed token: " + token);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(token);


private void scheduleJob() 
    // [START dispatch_job]
    //OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
    //        .build();
    //WorkManager.getInstance().beginWith(work).enqueue();
    // [END dispatch_job]


private void handleNow() 
    Log.d(TAG, "Short lived task is done.");


private void sendRegistrationToServer(String token)

    // TODO: Implement this method to send token to your app server.


private void sendNotification(String messageBody, String icon)


    String channelId = "General";
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setLargeIcon(getBitmapFromURL(icon))
                    .setContentTitle("Chapur")
                    .setSmallIcon(R.drawable.icon_agenda)
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());


public Bitmap getBitmapFromURL(String strURL) 
    try 
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection)
                url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
     catch (IOException e) 
        e.printStackTrace();
        return null;
    

【问题讨论】:

【参考方案1】:

我解决了。

private final static AtomicInteger c = new AtomicInteger(0);

    public static int getID() 
        return c.incrementAndGet();
    


private void sendNotification(String messageBody, String icon)


    String channelId = "General";
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setLargeIcon(getBitmapFromURL(icon))
                    .setContentTitle("Chapur")
                    .setSmallIcon(R.drawable.icon_agenda)
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(getID(), notificationBuilder.build());

【讨论】:

【参考方案2】:

你的问题是你总是在行中使用“0”作为你的通知 ID

notificationManager.notify(0, notificationBuilder.build());

如果你每次都给它一个新的id,你就不会有这个问题:)

【讨论】:

以上是关于如何使用 Firebase Cloud Messaging 在前台显示多个通知的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 PHP 在 Firebase 中自动导入存储桶 - Google Cloud Storage

如何使用 Firebase Cloud Messaging 在前台显示多个通知

如果用户长时间没有写入,如何使用 Firebase Cloud Functions 在 Firebase 数据库中设置节点的值?

如何使用 Firebase Cloud Messaging 向所有用户发送数据负载?

上传到 Firebase 存储时如何使用 Cloud Functions for FIrebase 获取 mp3 文件的持续时间

如何使用 Firebase Cloud Messaging 向所有设备发送通知