如何添加 fcm 通知



当应用程序在后台时,如何以收件箱样式添加 fcm 通知?

当我添加以下代码时,我在打开应用程序时得到收件箱样式

但如果应用程序是后台的,它会显示单独的通知

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    Integer notify_no = 0;
    Integer numMessages = 0;
    DBHelper db = new DBHelper(this);
    private final int notificationID = 237;
    private static int value = 0;
   // Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
    //Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.newlogo);

        // 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());
           /* Integer badge = Integer.parseInt(remoteMessage.getData().get("badge"));
            Log.d("notificationNUmber",":"+badge);
            setBadge(getApplicationContext(), badge);*/
        }
        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        Intent intent = new Intent();
        intent.setAction("com.ksoft.propreka.CUSTOM_INTENT");
        sendBroadcast(intent);
        db.insertNotification(remoteMessage.getNotification().getBody(),remoteMessage.getData().get("room_id"));
        //EventBus.getDefault().post(remoteMessage.getNotification().getBody());
        //
        try {
            if (remoteMessage.getNotification() != null) {
                sendNotification(remoteMessage.getData().get("text"));
            } else if (!remoteMessage.getData().isEmpty()) {
                sendNotification(remoteMessage.getData().get("text"));
            }
        } catch (Exception e) {
            Log.d("json error", e.toString());
        }
        //sendNotification(remoteMessage.getData().get("text"));
        Log.d("test",":test notification");
        //createpushnotification();
        // 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.
    }
    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    public void sendNotification(String messageBody) {
        Intent intent = new Intent(this,Main2Activity.class);
        intent.putExtra("messages","messages");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra("fcm_notification", "Y");
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);


        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("Propreka")
                .setSmallIcon(R.mipmap.new_logo)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(Uri.parse("content://settings/system/notification_sound"))
                .setVibrate(new long []{100,2000,500,2000})
                .setContentIntent(pendingIntent);

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        inboxStyle.setBigContentTitle(getResources().getString(R.string.app_name));
        Integer msg_count  = db.message_count();
        Integer chat_count = db.chat_count();
        inboxStyle.setSummaryText(" "+msg_count+" messages from "+chat_count+" chat");
        ArrayList<ArrayList> Newchat = db.getNotifications();
        for (ArrayList s : Newchat) {
            inboxStyle.addLine(s.get(0).toString());
        }
        notificationBuilder.setStyle(inboxStyle);
        NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
        /*Intent resultIntent = new Intent(getBaseContext(), Main2Activity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent piResult = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.new_logo)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(messageBody)
                .setVibrate(new long []{0,100,10,100})
                .setContentIntent(piResult);
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
       // String[] events = new String[6];
        inboxStyle.setBigContentTitle(getResources().getString(R.string.app_name));
        ArrayList<ArrayList> Newchat = db.getNotifications();
        for (ArrayList s : Newchat) {
            inboxStyle.addLine(s.get(0).toString());
        }
        mBuilder.setStyle(inboxStyle);
        nManager.notify(getResources().getString(R.string.app_name),0 ,mBuilder.build());*/

    }
    public void createpushnotification()
    {
        Log.i("Start", "notification");
   /* Invoking the default notification service */
        NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);
        mBuilder.setContentTitle("New Message");
        mBuilder.setContentText("You've received new message.");
        mBuilder.setTicker("New Message Alert!");
        mBuilder.setSmallIcon(R.mipmap.new_logo);
   /* Increase notification number every time a new notification arrives */
        mBuilder.setNumber(++numMessages);
   /* Add Big View Specific Configuration */
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        String[] events = new String[6];
        events[0] = new String("This is first line....");
        events[1] = new String("This is second line...");
        events[2] = new String("This is third line...");
        events[3] = new String("This is 4th line...");
        events[4] = new String("This is 5th line...");
        events[5] = new String("This is 6th line...");
        // Sets a title for the Inbox style big view
        inboxStyle.setBigContentTitle("Big Title Details:");
        // Moves events into the big view
        for (int i=0; i < events.length; i++) {
            inboxStyle.addLine(events[i]);
        }
        mBuilder.setStyle(inboxStyle);
   /* Creates an explicit intent for an Activity in your app */
        Intent resultIntent = new Intent(this, Main2Activity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(Main2Activity.class);
   /* Adds the Intent that starts the Activity to the top of the stack */
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
   /* notificationID allows you to update the notification later on. */
        mNotificationManager.notify(notificationID, mBuilder.build());
    }
}

如何添加收件箱样式?

使用数据负载发送通知数据,并使用此类向手机显示。

例如:

使用通知有效负载

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    }
  }

当应用处于后台时,此数据将显示 Firebase 向手机发送的默认通知,但当应用处于前台时,将调用 FirebaseMessagingService Firebase 向手机发送onMessageReceived方法。

使用数据有效负载

每次发送通知时onMessageReceived都会调用该方法。因此,您可以根据需要构建通知。

{
   "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   },
 }

有关更多详细信息,请转到此处的官方文档。

有两种类型的 FCM 消息。

  • 通知消息。
  • 数据消息。

FCM

发送数据消息,然后它将出现在您的调用方法中。

当应用程序在后台时,FCM 不调用 onMessageReceived 方法。而不是显示默认通知。

相关内容

  • 没有找到相关文章

最新更新