繁体   English   中英

如何在Android上用自己的Firebase通知替换通知?

[英]How to replace firebase notification with your own on Android?

我的Android应用程序收到了Firebase通知。 而且我需要本地化此通知,具体取决于客户端而非服务器端的应用程序语言。

如果应用程序在前台,则使用FirebaseMessagingService onMessageReceived()并推送我自己的本地化通知。 但是,如果应用程序在后台,则不会调用onMessageReceived()

在这种情况下,我使用我自己的类扩展的BroadcastReceiver onReceive(Context context, Intent intent)方法捕获通知,我将其本地化并推送。 一切顺利,但最后我得到了2个推送通知:我自己的本地化版本和Firebase。

我如何摆脱此Firebase通知并仅获得我自己的通知?

public class FirebaseDataReceiver extends BroadcastReceiver {

Context context;
PendingIntent pendingIntent;

public void onReceive(Context context, Intent intent) {
    this.context = context;
    Bundle dataBundle = intent.getExtras();
    String title = "";
    String body = "";
    String type = "";
    String objectId = "";

    if (dataBundle != null) {
        type = dataBundle.getString("type");
        objectId = dataBundle.getString("objectId");
        title = NotificationUtils.getNotificationTitle(context, dataBundle);
        body = NotificationUtils.getNotificationBody(context, dataBundle);
    }

    Intent newIntent = new Intent(context, TutorialActivity_.class);
    newIntent.putExtra("target", "notification");
    newIntent.putExtra("type", type);
    newIntent.putExtra("objectId", objectId);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    pendingIntent = PendingIntent.getActivity(context,
            0,
            newIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new Notification.Builder(context)
            .setContentTitle(title)
            .setContentText(body)
            .setPriority(Notification.PRIORITY_HIGH)
            .setDefaults(Notification.DEFAULT_ALL)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setSmallIcon(R.drawable.splash_mini)
            .build();

    deleteLastNotification();
    NotificationManagerCompat.from(context).notify(0, notification);
}
}

您应该真正使用来自服务器的数据通知。 普通消息通知无法实现您想要的这种行为。 在此处查看文档: https : //firebase.google.com/docs/cloud-messaging/concept-options

因此,您从服务器向Firebase的请求应如下所示:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}

代替:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM