java - android应用程序在后台时如何从firebase-message获取数据
问题描述
我正在使用 firebase 控制台发送 firebase 消息。消息应包含如下所示的附加数据,目的是在我的应用程序的 web 视图中打开特定的 url:
我设置了清单和 firebase 类来获取消息。在我的 firebase 类中,我尝试获取数据:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(remoteMessage.getData().containsKey("key1")) {
intent.putExtra("destination", remoteMessage.getData().get("key1"));
}
PendingIntent pendingIntent = PendingIntent.getActivity
(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String channelId = "default";
NotificationCompat.Builder builder;
if (remoteMessage.getNotification() != null ) {
if (remoteMessage.getNotification().getTitle() != null) {
builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_onesignal_default)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
} else {
builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_onesignal_default)
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
}
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "default", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}
在我的 MainActivity 类中,我尝试获取数据。当应用程序在前台时,以下工作(无论打开什么活动,它都会跳转到 MainActivity 并执行以下内容):
@Override
protected void onNewIntent(Intent intent) {
if (intent.getExtras() != null) {
Bundle extras = intent.getExtras();
if(extras.containsKey("destination")) {
Log.e("FIREBASE_CONTAINS", (String) extras.get("destination"));
}
}
}
但是如果应用程序从后台启动,则不会触发该事件。我试图获取意图并检查活动的 onResume() 事件中的密钥,但它不起作用(在 inCreate() 和 onStart() 中相同)。
有谁能够帮助我?
- - - - - - 编辑 - - - - - - - - -
正如其中一条评论所描述的,问题似乎是 Notification-Messages 不会到达 onMessageReceived() 事件。显然,firebase 控制台无法发送数据通知(将到达事件),所以我尝试使用 POSTMAN。我已经读到我必须将通知标签从消息正文中删除,并将我的所有信息放在数据部分中。但是如果我这样做,消息将不会重新发送到我的应用程序(当我再次添加通知部分时,它们会发送消息,但在这种情况下它们当然不会到达 onMessageReceived() 事件)。
解决方案
推送消息有 3 种类型
- 通知
- 数据
- 和两者
推送消息基本上是一个 json 有效负载:
payload:{
notificacion...
data
}
每种推送消息的规则是不同的。在您的情况下,您正在使用 Firebase Web 控制台并添加自定义数据,这意味着您的有效负载将包含通知和数据。
对于组合类型,背景中的行为是使用默认通知(NotificationCompat,视觉类型)并打开清单中注册的默认活动。在活动中,您可以获取数据。
假设您的默认活动称为 MainActivity
public class MainActivity {
onCreate...{
//... usual stuff
Intent fcmIntent = getIntent();
if fcmIntent != null
//check the extras and forward them to the next activity if needed
}
}