2017-02-16 10 views
1

Я использую Firebase Cloud Messaging для отправки push-уведомлений с моего сервера на мое приложение для Android.Как собирать уведомления о облачных сообщениях Firebase, когда приложение не работает?

Когда приложение запущено, уведомления уложены в, потому что я установил их в группу в моем FirebaseMessagingService. Это хорошо.

Однако, когда приложение не работает, уведомления не складываются, и каждый из них отображается отдельно. Что не приятно.

Как убедиться, что уведомления сложены даже в том случае, если приложение не работает?

Это как мой FirebaseMessagingService выглядит следующим образом:

public class MyFcmListenerService extends FirebaseMessagingService { 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     RemoteMessage.Notification notification = remoteMessage.getNotification(); 

     Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 

       .setSmallIcon(R.drawable.notif_white) 
       .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.notif_white)) 
       .setContentTitle(getResources().getString(R.string.app_name)) 
       .setContentText(notification.getBody()) 
       .setAutoCancel(true) 
       .setPriority(2) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent) 
       .setGroup("1") 
       .setGroupSummary(true) 
       .setOnlyAlertOnce(true); 


     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(0 , notificationBuilder.build()); 

     } 
    } 
+0

Не могли бы вы предоставить какой-то код, где вы будете обрабатывать входящий беспорядок возрастов и создать уведомление? – glethien

+0

Добавлен код, пожалуйста, проверьте его. –

+0

@ The Cook Привет, я сталкиваюсь с такой же проблемой, нашел ли у вас какое-либо решение для этого? – murli

ответ

3

Чтобы сложить два или более уведомлений (указанный в списке сообщений) и сделать их как уведомления в стиле GMail, вы можете добавить стиль почты для уведомления, как показано ниже: -

private void showNotification(Context mContext, String title, List messages, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) { 

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
      mContext); 

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); 

    for(int i=0;i<messages.size();i++) 
     inboxStyle.addLine(messages.get(i)); 

    Notification notification; 
    notification = mBuilder.setTicker(title) 
      .setAutoCancel(true) 
      .setContentTitle(title) 
      .setContentIntent(resultPendingIntent) 
      .setSound(alarmSound) 
      .setStyle(inboxStyle) 
      .setWhen(getTimeMilliSec(timeStamp)) 
      .setSmallIcon(R.drawable.notification_small_icon) 
      .setLargeIcon(R.drawable.notification_large_icon) 
      .setDeleteIntent(PendingIntent.getBroadcast(mContext,101,new Intent(mContext, NotificationDismissedReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT)) 
      .build(); 

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.notify(NConfig.NOTIFICATION_ID, notification); 
    } 

Если вы заметили, я также добавил удалить намерение для моего уведомления, которое вызывает NotificationDismissedReceiver (BroadcastReceiver), чья основная задача заключается в четкие уведомлениях сообщения, которые были отклонены по прикосновению жест, так что в следующий раз только новые сообщения уведомлений получат стек вместе.

public class NotificationDismissedReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 
    // TODO: This method is called when the BroadcastReceiver is receiving 
    // an Intent broadcast. 
    messages.clear(); 
} 
} 

Основная логика собрать все непрочитанные/unswiped уведомления внутри списка т.е. сообщения, ниже onMessageReceive() из FirebaseMessagingService: -

public void onMessageReceived(RemoteMessage remoteMessage) { 
    Log.e(TAG, "From: " + remoteMessage.getFrom()); 

    if (remoteMessage == null) 
     return; 

    if (remoteMessage.getData()!=null && remoteMessage.getData().size() > 0) 
    { 

     try { 
      JSONObject json = new JSONObject(remoteMessage.getData().toString()); 
      Log.e(TAG, "Notification Data: " + json); 
      Title = json.get("title").toString(); 
      Message = json.get("body").toString(); 
      messages.add(Message); 

     } catch (Exception e) { 
      Log.e(TAG, "Exception: " + e.getMessage()); 
     } 
    } 

     showNotification(...); 
    } 

Когда приложение находится на переднем плане, выше onMessageReceive() FirebaseMessagingService выполняется отлично, но когда ваше приложение находится в фоновом режиме или убито, оно не выполняется. Для того, чтобы это выполнить, вы должны опустить уведомление часть из сообщения JSON отправленного со стороны сервера и включаете только часть данных, как показано ниже: -

 var data = new 
     { 
      to = token, 
     // notification = new 
     // { 
     //  body = messageBody, //Omitting notification part of data 
     //  title = messageTitle, 
     //  icon = "myicon", 
     //}, 
     data = new 
     { 
       body = messageBody, // adding all notification information inside data 
       title = messageTitle, 
       icon = "myicon", 
      } 
     }; 

Делая это ваше сообщение теперь становится сообщением данных только что означает что он всегда будет выполнять onMessageReceive() FirebaseMessagingService независимо от того, находится ли ваше приложение в фоновом режиме или на переднем плане.

Надеюсь, это объяснение поможет.

1

Firebase не будет звонить вашему onMessageReceived, когда ваше приложение находится в фоновом режиме или убито, и вы не можете настроить свое уведомление. Появится сообщение сгенерированного системой.

сделать Firebase библиотеку для вызова onMessageReceived в каждом случае

а) переднего плана

б) Фон

с) Убитые

вы не должны ставить JSON ключ "уведомление" в ваш запрос к API Firebase, но вместо этого используйте «данные», см. ниже.

Например, следующее сообщение не будет вызывать onMessageReceived()

{ 
    "to": "/topics/test", 
    "notification": { 
    "title" : "title", 
    "message": "data!" 
    } 
} 

, но это будет работать

{ 
    "to": "/topics/test", 
    "data": { 
     "title":"title", 
     "message":"data!" 
    } 
} 

см this имеет подробное описание firebase типа сообщения, например:

@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 

    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()); 
     sendNotification(remoteMessage.getData().get("message").toString(), remoteMessage.getData().get("title").toString()); 
    } 

} 

private void sendNotification(String message, String title) { 
     int requestID = (int) System.currentTimeMillis(); 
     Intent intent = new Intent(this, activityCompat); 

     PendingIntent pendingIntent = PendingIntent.getActivity(this, requestID, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.small_logo) 
       .setContentTitle(title) 
       .setContentText(message).setContentIntent(pendingIntent) 
       .setAutoCancel(true) 
       .setStyle(new NotificationCompat.BigTextStyle() 
         .bigText(messageBody)) 
       .setTicker(messageBody); 

     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL; 
     Notification notification = notificationBuilder.build(); 

     notificationManager.notify(0, notification); 

}