【问题标题】:Firebase notification doesn't work properly if application is in background [duplicate]如果应用程序在后台,Firebase 通知将无法正常工作 [重复]
【发布时间】:2017-02-03 00:36:29
【问题描述】:

我有一个 Firebase 的 FirebaseMessagingService 类:

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);

对于任何其他活动类,它不会打开我指定的类,而是打开我在后台打开的最后一个类。

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

提前致谢。

【问题讨论】:

标签: android firebase firebase-cloud-messaging firebase-notifications


【解决方案1】:

这是因为如果您的应用在后台处理通知的方式不同。

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

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

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

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

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

【讨论】:

  • 可以理解,如何在服务器上设置图标?同样对于意图类问题,我该如何管理?
  • @MahmoudTarek 那些应该是活动的类,应该在清单文件中注册。
  • 已更新答案以具有通知模板 请接受答案。
  • 谢谢,“icon”属性有效,但仅适用于小图标,我怎样才能从对象本身获得大图标?
  • 好像不支持大图标ATM。在这里查看更多信息github.com/firebase/quickstart-android/issues/84请接受答案
猜你喜欢
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
相关资源
最近更新 更多