Firebase onMessageReceived not called when app in background

前端 未结 26 2642
粉色の甜心
粉色の甜心 2020-11-22 02:32

I\'m working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appe

26条回答
  •  伪装坚强ぢ
    2020-11-22 03:14

    I had the same problem. It is easier to use the 'data message' instead of the 'notification'. The data message always load the class onMessageReceived.

    In that class you can make your own notification with the notificationbuilder.

    Example:

     @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
        }
    
        private void sendNotification(String messageTitle,String messageBody) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    
            long[] pattern = {500,500,500,500,500};
    
            Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    
            NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setContentTitle(messageTitle)
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setVibrate(pattern)
                    .setLights(Color.BLUE,1,1)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
    
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
        }
    

提交回复
热议问题