如何在应用程序未运行时堆叠Firebase云消息通知? [英] How to stack Firebase Cloud Messaging notifications when the application is not running?

查看:136
本文介绍了如何在应用程序未运行时堆叠Firebase云消息通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase Cloud Messaging 从我的服务器向我的android应用程序发送推送通知。

运行应用程序时,通知是堆叠的,因为我将它们设置为我的 FirebaseMessagingService 。这是很好的。



然而,当应用程序没有运行,通知是不堆叠,每一个都单独出现。这是不好的。



如何确保即使应用程序没有运行通知堆叠?

这就是我的 FirebaseMessagingService 的样子:

  public class MyFcmListenerService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage){
RemoteMessage.Notification notification = remoteMessage.getNotification();

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)

.setSmallIcon(R.drawable.notif_white)
.setLargeIcon(BitAppFactory.decodeResource(getApplicationContext()。getResources ),R.drawable.notif_white))
.setContentTitle(getResources()。getString(R.string.app_name))
.setContentText(notification.getBody())
.setAutoCancel(true )
.setPriority(2)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setGroup(1)
.setGroupSummary(true)
.setOnlyAlertOnce(true);


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


$ b $ / code $ / pre

解决方案

要堆叠两个或更多通知(在消息列表中指定),并使其显示为GMail样式的通知,您可以为通知添加收件箱样式,如下所示: - $ / $>

  private void showNotification(Context mContext,String title,List messages,String timeStamp,PendingIntent resultPendingIntent,Uri alarmSound){
$ b $ final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);

NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

for(int i = 0; i< messages.size(); i ++)
inboxStyle.addLine(messages.get(i));

通知通知;
notification = mBuilder.setTicker(title)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)$ b $ .setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(R.drawable.notification_small_icon)
.setLargeIcon(R.drawable.notification_large_icon)
。 setDeleteIntent(PendingIntent.getBroadcast(mContext,101,new Intent(mContext,NotificationDismissedReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT))
.build();

NotificationManager notificationManager =(NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NConfig.NOTIFICATION_ID,notification);





$ b如果你注意到,我还添加了删除意图,我的通知会触发NotificationDismissedReceiver (BroadcastReceiver),其主要工作是清除已被滑动手势解散的通知消息,以便下一次只有新通知消息堆叠在一起。

  public class NotificationDismissedReceiver extends BroadcastReceiver {

@Override $ b $ public void onReceive(Context context,Intent intent){
// TODO: BroadcastReceiver正在接收
//一个Intent广播。
messages.clear();






主要逻辑是收集所有未读/未保存的通知在消息列表里面,下面是FirebaseMessagingService的onMessageReceive(): -
$ b $ pre $ public $ onMessageReceived(RemoteMessage remoteMessage){
Log.e(TAG,From:+ remoteMessage.getFrom());

if(remoteMessage == null)
return;

if(remoteMessage.getData()!= null&& remoteMessage.getData()。size()> 0)
{

try {
JSONObject json = new JSONObject(remoteMessage.getData()。toString());
Log.e(TAG,通知数据:+ json);
Title = json.get(title)。toString();
Message = json.get(body)。toString();
messages.add(Message); (例外e){
Log.e(TAG,Exception:+ e.getMessage());

}
}
}

showNotification(...);



$ b当应用程序处于前台时,FirebaseMessagingService的上述onMessageReceive()将执行正常但是当你的应用程序在后台或被杀时不能执行。
要使其执行,您必须从服务器端发送的JSON消息中省略通知部分,并仅包含数据部分,如下所示: - $ /

$ $ $ p> var data = new
{
to = token,
// notification = new
// {
// body = messageBody ,//省略数据的通知部分
// title = messageTitle,
// icon =myicon,
//},
data = new
{
body = messageBody,//添加数据中的所有通知信息
title = messageTitle,
icon =myicon,
}
};




$ b

通过这样做,您的消息现在变成了数据消息,这意味着它将始终执行onMessageReceive() FirebaseMessagingService,无论你的应用程序是在后台还是前台。



希望这个解释有帮助。


I am using Firebase Cloud Messaging to send push notifications from my server to my android application.

When the application is running, the notifications are stacked because I set them to a group in my FirebaseMessagingService. Which is nice.

However, when the application is not running, the notifications are not stacked and each one appears individually. Which is not nice.

How to make sure notifications are stacked even when the application is not running?

This is how my FirebaseMessagingService looks like:

public class MyFcmListenerService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        RemoteMessage.Notification notification = remoteMessage.getNotification();

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)

                .setSmallIcon(R.drawable.notif_white)
                .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.notif_white))
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(notification.getBody())
                .setAutoCancel(true)
                .setPriority(2)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent)
                .setGroup("1")
                .setGroupSummary(true)
                .setOnlyAlertOnce(true);


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

        }
    }

解决方案

To stack two or more notifications(specified in messages list) and to make them appear like GMail style notifications, you can add inbox style for your notification, like below:-

    private void showNotification(Context mContext, String title, List messages, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    for(int i=0;i<messages.size();i++)
        inboxStyle.addLine(messages.get(i));

    Notification notification;
    notification = mBuilder.setTicker(title)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.drawable.notification_small_icon)
            .setLargeIcon(R.drawable.notification_large_icon)
            .setDeleteIntent(PendingIntent.getBroadcast(mContext,101,new Intent(mContext, NotificationDismissedReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT))
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NConfig.NOTIFICATION_ID, notification);
    }

If you notice, i have also added delete intent for my notification which triggers NotificationDismissedReceiver(BroadcastReceiver) whose main job is to clear notifications messages that have been dismissed by swipe gesture, so that next time only new notification messages get stack together.

public class NotificationDismissedReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving
    // an Intent broadcast.
    messages.clear();
}
}

The main logic is to collect all unread/unswiped notifications inside a list i.e messages, below is onMessageReceive() of FirebaseMessagingService :-

    public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "From: " + remoteMessage.getFrom());

    if (remoteMessage == null)
        return;

    if (remoteMessage.getData()!=null && remoteMessage.getData().size() > 0) 
    {

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            Log.e(TAG, "Notification Data: " + json);
            Title = json.get("title").toString();
            Message = json.get("body").toString();
            messages.add(Message);

        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
     }

       showNotification(...);
     }

When the application is in foreground, the above onMessageReceive() of FirebaseMessagingService executes fine but when your application is in background or killed it doesn't execute. To make it execute you have to omit notification part from the JSON message sent from server side and only include the data part, as shown below:-

       var data = new
       {
           to = token,
        //   notification = new
        //   {
        //       body = messageBody,   //Omitting notification part of data
        //       title = messageTitle,
        //       icon = "myicon",
        //},
        data = new
        {
               body = messageBody,  // adding all notification information inside data
               title = messageTitle,
               icon = "myicon",
           }
       };

By doing this your message now becomes data message only which means that it will always execute onMessageReceive() of FirebaseMessagingService irrespective of whether your app is in background or foreground.

Hope this much explanation helps.

这篇关于如何在应用程序未运行时堆叠Firebase云消息通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆