简体   繁体   中英

Notification android (FCM)

I want to customize notification layout when app closed and notification arrives a default notification is shown where I want a custom notification to be displayed even if app the closed.

The following is my code for Firebase onMessageReceievd

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d("remoteMessage",String.valueOf(remoteMessage.getFrom()));

        if (remoteMessage.getData().size() > 0) {
            Log.e("MyFirebaseMsgService", "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                sendPushNotificationData(json);
            } catch (Exception e) {
                Log.e("MyFirebaseMsgService", "Exception: " + e.getMessage());
            }
        }

        if (remoteMessage.getNotification() != null) {
            //Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            sendPushNotification(String.valueOf(remoteMessage.getNotification().getBody()),String.valueOf(remoteMessage.getNotification().getTitle()));
        }
    }

I used BitTextStyle() to add highlighted text in notification.

return new NotificationCompat.Builder(context)
       .setSmallIcon(R.drawable.ic_mono)
       .setContentTitle(title)
       .setContentText(message)
       .setLargeIcon(icon)
       .setColor(ContextCompat.getColor(context, R.color.notification_color))
       .setStyle(new NotificationCompat.BigTextStyle().bigText(title))
       .setStyle(new NotificationCompat.BigTextStyle().bigText(message).setSummaryText("#hashtag"))
       .setShowWhen(true)
       .setAutoCancel(true);

Firebase Remote message has notification and data fields. According to this documentation Firebase handles remoteMessage.notification automatically and pass remoteMessage.data into intent extras when your app is closed. But when your app is active remoteMessage comes to your receiver and handled by it. But there are few scenarios which depends on remoteMessage state. See the table in documentation. So, if you want to handle all notification even when your app is closed, you need to put all your data into remoteMessage.data field. In this case Firebase will deliver remote message directly into your receiver and there you can create custom layout with your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM