【发布时间】:2017-12-21 11:17:45
【问题描述】:
Firebase 提供了两种发送推送通知的方法,一种是使用它的 firebase 控制台,另一种是使用像以前在 GCM 中那样的服务器。现在我们正在将我们的服务器从 GCM 转换为 Firebase,我们需要在应用中接收和显示 FCM 通知。
我已经完成了官方 firebase 网站的实现,并完成了示例代码,但我被困在这部分。当我们的服务器将推送通知发送到 Firebase 并将 Firebase 发送到我的应用程序时,我会在 onMessageReceived 方法中收到带有 RemoteMessage 参数的通知。我知道消息在 RemoteMessage 参数中,但我在 Firebase 官方文档中找不到任何指南或示例代码,说明如何处理此问题以在 android 设备通知栏上显示通知文本。
正如您在官方指南中看到的那样,没有说明如何从 RemoteMessage 参数中毫无问题地提取消息。我知道您可以在里面搜索并找到字符串,但我想找到有关如何正确安全地处理此问题的官方指南。
在官方文档中你只有这个:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
// Handle message within 10 seconds
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
还有这个(指南上没有提到):
private void sendNotification(String messageBody) {
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)
.setSmallIcon(R.drawable.ic_main)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
【问题讨论】:
-
检查this
-
好帖子@Maddy 我会仔细阅读的
-
很高兴为您提供帮助:)
标签: android firebase push-notification firebase-cloud-messaging android-push-notification