Gor*_*992 7 android push-notification firebase google-cloud-messaging
我遇到FireBase推送通知问题.当我的应用程序在后台时,通知即将到来,但是当我的应用程序在前台时我没有收到通知,但在控制台中显示通知,这意味着通知在这里,但它没有显示在通知栏中.你可以帮帮我吗?
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("OnMessage", "Received");
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From " + remoteMessage.getFrom());
Log.d(TAG, "Body " + remoteMessage.getNotification().getBody());
String aa=remoteMessage.toString();
Intent intent=new Intent(MyFirebaseMessagingService.this, MainActivity.class);
intent.putExtra("msg", aa);
sendNotification(remoteMessage);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentText(remoteMessage.getNotification().getBody());
// remoteMessage.getNotification().getBody();
}
private void sendNotification(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我刚刚注意到,当您从控制台发送通知并且您的应用程序位于前台时,不会调用 FirebaseMessagingService 的 onMessageReceived() (截至目前)。一种解决方案是您可以使用Firebase API发送推送通知,无论应用程序位于前台还是后台,它都会调用 onMessageReceived()。
如果您使用“通知”正文发送推送通知,即
notification: {
title: "notification title",
icon: "ic_launcher",
color: "#4E2AA5",
body: "notification body"
}
Run Code Online (Sandbox Code Playgroud)
要在 onMessageReceived() 中检索此信息,请使用如下内容:
String color = remoteMessage.getNotification().getColor();
String body = remoteMessage.getNotification().getBody();
String title = remoteMessage.getNotification().getTitle();
String icon = remoteMessage.getNotification().getIcon();
Run Code Online (Sandbox Code Playgroud)
如果您的应用程序处于后台,Firebase 将显示与您在推送中设置的数据相对应的通知,并且还将调用 onMessageReceived()。因此,如果您还编写了在 onMessageReceived() 中显示自定义通知的代码,您将看到 2 个通知。
要解决此问题,您可以使用一些“数据”键,如下所示:
data: {
title: "notification title",
body: "notification body"
}
Run Code Online (Sandbox Code Playgroud)
并在 onMessageReceived() 中检索它,请使用如下内容:
Map<String, String> map = remoteMessage.getData();
for (Map.Entry<String, String> entry : map.entrySet()) {
Log.d(TAG, entry.getKey() + "/" + entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以构建自己的自定义通知并从 onMessageReceived() 中显示它,只有该通知才会显示。
PS如果有帮助请投票。我是 stackoverflow 的新手。
| 归档时间: |
|
| 查看次数: |
8615 次 |
| 最近记录: |