android - 应用程序在前台使用 Firebase 时不显示通知
问题描述
我正在使用来自服务器的firebase推送通知,但是当应用程序在前台时,通知不显示请帮助我
解决方案
请参阅官方链接以获取完整参考。
如果您打算根据收到的 FCM 生成自己的通知,请执行以下操作
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// 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.
sendNotification(remoteMessage.getNotification().getBody());// or pass value fetched from data payload
...
}
然后像这样的delcare通知生成器,
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);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
推荐阅读
- asp.net - 无法将控制台应用程序连接到 SQLExpress
- api - 查看网页调用的 API
- git - git 成功推送到私有 github 存储库,即使令牌过期
- c# - 每次我在 WPF 中加载时如何使 Listbox 的 ScrollViewer 滚动到顶部
- python - 如何通过 Telethon 加入群组通话?
- python - OpenCV逆warpPolar输出帧外
- php - 在 Laravel 中仅允许带有验证的数字和浮点值
- python - 测试模型的程序没有显示没有错误
- linux - 如何在linux后台运行telnet进程
- jquery - jQuery - 取消静音和设置音量