应用在后台时的Android通知

我正在从谷歌firebase发送针对Android 5.0的Android应用程序的推送通知:

我的推送通知代码是:

@Override public void onMessageReceived(RemoteMessage remoteMessage) { String badge = "0"; Uri uri = Uri.parse( getString(R.string.app_host_name) ); Map data = remoteMessage.getData(); if (data.size() > 0) { try { uri = Uri.parse( data.get("link") ); badge = data.get("badge"); } catch (NullPointerException e) { // } } if (remoteMessage.getNotification() != null) { RemoteMessage.Notification notification = remoteMessage.getNotification(); sendNotification(notification.getTitle(), notification.getBody(), uri.toString(), badge); } } private void sendNotification(String title, String body, String url, String badge) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (Patterns.WEB_URL.matcher(url).matches()) { intent.putExtra("link", url); } PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ); Resources resources = getApplicationContext().getResources(); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "default") .setColor( resources.getColor(R.color.colorPrimaryDark) ) .setSmallIcon( R.drawable.ic_stat_icon ) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setNumber(Integer.parseInt(badge)) .setLargeIcon( BitmapFactory.decodeResource( resources, R.mipmap.ic_launcher ) ) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= 26) { NotificationChannel notificationChannel = new NotificationChannel( "default", "Main notification channel", NotificationManager.IMPORTANCE_HIGH ); notificationManager.createNotificationChannel( notificationChannel ); } notificationManager.notify( 1, notificationBuilder.build() ); } 

当应用程序处于活动/打开/不在后台时,一切都非常完美,但是当它不是时,通知不会被分组,没有显示数字,并且对所有这些设置都没有反应,我能够改变通过清单设置只是小图标和圆形颜色

    

但为什么? 这就像应用程序处于后台通知时不使用活动代码中的设置,而是仅使用AndroidManifest中的某种“默认”设置。

正如你在评论中所说:

当应用程序在后台时,应用程序没有采用setNumber,setAutoCancel,setSmallIcon,setLargeIcon选项

这是因为您正在使用通知有效负载来发送仅在前台触发的通知。

因此,当您的应用在后台时,它不会进入此方法。

要解决这个问题,您可以单独使用data负载:

 "data": { "titles": "New Title", "bodys": "body here" } 

因为当你的应用程序处于前台/后台时,数据有效负载将进入onMessageReceived()

然后在fcm中你可以这样做:

  if (remoteMessage.getData().size() > 0) { title = remoteMessage.getData().get("titles"); body = remoteMessage.getData().get("bodys"); }