如果应用程序在后台,Firebase 通知将无法正常工作

Firebase notification doesn't work properly if application is in background

我有一个用于 Firebase 的 FirebaseMessagingService class:

public class FcmMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    String message = remoteMessage.getNotification().getBody();

    Map<String, String> params = remoteMessage.getData();

    Bitmap remote_picture = null;
    remote_picture = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.logo);

    intent = new Intent(this, HomeDrawer.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle("Notification Title");
    notificationBuilder.setContentText(message);
    notificationBuilder.setSmallIcon(R.drawable.ic_notif);
    notificationBuilder.setLargeIcon(remote_picture);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification noti = new Notification();
    noti = notificationBuilder.build();
    //notificationBuilder.setVibrate(new long[] { 1000, 1000});
    //notificationBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
    noti.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
    notificationManager.notify(0,noti);

    super.onMessageReceived(remoteMessage);
}

如果应用程序在后台,(没有主动打开,但在后台,没有关闭)通知smallIcon和LargeIcon不会出现,而是出现android的默认通知,如果我已更改

 intent = new Intent(this, HomeDrawer.class);

对于任何其他 activity class,它不会打开我指定的 class 并打开我在后台打开的最后一个 class。

我做错了什么?如果后台 SmallIcon 和 LargeIcon 不能正常工作。但是,通知消息看起来很好,而且 remoteMessage.getData();正确获取数据,都是关于图标和意图的行为class。

提前致谢。

发生这种情况是因为如果您的应用程序在后台,通知的处理方式会有所不同。

如果应用 运行 在前台,那么你的 FcmMessagingService 将被执行,你将自己处理通知。

如果应用不是 运行,通知由 android 系统本身处理。FcmMessagingService 永远不会执行。对于这种情况,您必须在服务器上正确设置图标!

我相信这种行为是在引入 doze 机制后发生的。

从服务器发送的通知应该是这样的

"notification" : {
  "body" : "great match!",
  "title" : "Portugal vs. Denmark",
  "icon" : "myicon", // the name of the resource
  "sound" : "mySound"
}