0

How to add the fcm notification in inbox style when app is in background?

When i add the the below code i got inbox style when app is open

but if the app is background it showing seperate notification

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

how to add the inbox style?

AL.
  • 36,815
  • 10
  • 142
  • 281
jithin
  • 13
  • 3

2 Answers2

0

There is two type of FCM messages.

  • Notification Message.
  • Data Messages.

FCM

Send data message, then it will come in your call method.

When application in background then, FCM not call the onMessageReceived method. Instead of it display the default notification.

Jarvis
  • 1,714
  • 2
  • 20
  • 35
0

Use data payload to send the notification data and show it the phone using this class.

For example:

With Notification payload

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

This data will show default notification to the phone by the firebase when the app is in background but the onMessageReceived method from FirebaseMessagingService will be called when app is in foreground.

With data payload

Everytime you send notification onMessageReceived method will be called. So you can build notification as you want.

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

For more detail head out to the the official documentation here.

Community
  • 1
  • 1
Aawaz Gyawali
  • 3,244
  • 5
  • 28
  • 48
  • Thanks I used data payload instead of notification payload now its working properly when app in in background@Aawaz Gyawali – jithin Jun 15 '17 at 05:00