我在我的应用程序中发送推送通知,并希望即使应用程序已经在运行也能够显示它们,因此我尝试使用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");
}它从不打印最后一行(“一切都很好”),但也不会给出错误,所以即使它不能工作,它似乎也能工作。问题是什么,我该如何修复它?
发布于 2020-07-13 17:45:13
最近似乎有一个更新,它需要你运行一些额外的代码,以便它在更新的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());https://stackoverflow.com/questions/62859647
复制相似问题