使用NotificationManager未显示通知



我正在我的应用程序中发送推送通知,即使应用程序已经在运行,我也希望能够显示它们,因此我尝试使用onMessageReceived((函数。每当我发送通知时,该函数就会运行,我可以看到通知的标题和正文是正确的,所以到目前为止没有问题。然后我想在用户设备上弹出通知,但由于某种原因,我无法让它工作。我看了很多网站和stackoverflow问题,所有的代码看起来基本上都一样,所以有点困惑为什么它不适合我。

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
System.out.println("TITLE_IS: " + messageTitle);
System.out.println("MESSAGE_BODY: "+ messageBody);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody);
//Sets ID for the notification
int mNotificationId = (int) System.currentTimeMillis();

NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
System.out.println("Everything went fine");
}

它从不打印最后一行("一切都很好"(,但也不会给出错误,所以即使没有,它似乎也能工作。问题出在哪里?我该如何解决?

最近似乎有一个更新,需要运行一些额外的代码才能在更新的android版本上运行。所以代码应该看起来像:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_challenge)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
//to show notification do this
//Sets ID for the notification
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Tic-Tac-Toe";
NotificationChannel channel = new NotificationChannel(
channelId,
"Tic-Tac-Toe",
NotificationManager.IMPORTANCE_HIGH);
mNotifyMgr.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotifyMgr.notify(mNotificationId, mBuilder.build());

相关内容

  • 没有找到相关文章

最新更新