Tuesday, November 1, 2016

[Android][Resolved] remoteMessage.getData().get("message") return null

Source code

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        showNotification("null:"+remoteMessage.getData().get("message"));
    }

    private void showNotification(String message) {
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle("FCM Test")
                .setContentText(message)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0,builder.build());
    }
}

If you get this situation, you can check is the sentence remoteMessage.getData().get("message") return null first, if that's null then use other syntax to get the notification message :
if (remoteMessage.getData().get("message") != null) {
        showNotification( remoteMessage.getData().get("message") );
} else if((remoteMessage.getNotification().getBody() != null)) {
        showNotification( remoteMessage.getNotification().getBody() );
} else {
        Log.d("FCM error","Can receive message but can't get content from FCM");
}

Reference

http://stackoverflow.com/questions/37358462/firebase-onmessagereceived-not-called-when-app-in-background

No comments :

Post a Comment