我的应用程序可以正确接收到通知,但无法在接收到信息时弹出通知窗口(如果应用程序已经打开)。
注:如果应用程序在后台运行,则通知将显示正常。
我的代码:
我在此方法中接收通知:
@Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.d(TAG, "From: " + remoteMessage.getFrom());
if(remoteMessage!=null)
{
String id = null;
String title = null;
String body = null;
String launchPage = null;
if(remoteMessage.getNotification()!=null)
{
title = remoteMessage.getNotification().getTitle();
body = remoteMessage.getNotification().getBody();
}
if(remoteMessage.getMessageId()!=null)
{
id = remoteMessage.getMessageId();
}
Log.i(TAG, "id: " + id);
Log.i(TAG, "title: "+ title);
Log.i(TAG, "body: " + body);
int notif_id = 0;
sendNotification(notif_id, title, body, launchPage);
}
}
然后它调用这个函数(我理解为显示通知的函数):
private void sendNotification(int id, String title, String messageBody, String launchPage)
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle("OMR - "+title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setChannelId(CHANNEL_ID);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel(notificationManager, CHANNEL_ID);
}
Toast.makeText(this, "Received a notif...", Toast.LENGTH_SHORT).show();
//this line is not showing a notification
notificationManager.notify(id, notificationBuilder.build());
}
Firebase通知
{
"data": {
"message": "data payload only used to force using OnMessageReceived() if in BACKGROUND",
"notif_id": 1
},
"to" : "e04OAVaRw30:APA91bGyv5_tt4IWRkurjlqkqNlCxTBV8oRne18tQ5puniHPItOMgg11kdt56t5jfZnasb4Ms-tH9xUgWQhHy2eM487llRtlM9_V_PoWJI9KSr6XgCaysiDyS",
"notification": {
"title": "Notification",
"body": "This is Notification 2",
"sound":"default"
}
}
结果
- 通知已正确构建
- 声音播放正确
- 通知被放置在系统托盘中
- 但没有弹出通知窗口(我必须显示自定义对话框)
我的问题在于这行特定的代码
notificationManager.notify(id, notificationBuilder.build());
目前通知无法显示。
更新 我已经阅读了有关Android通知的更多信息,详情请参见
https://developer.android.com/guide/topics/ui/notifiers/notifications
发现只有通知抽屉中才会显示通知,而没有弹出(如“悬浮式通知”)。
根据这个问题,如果给通知添加高优先级,则可以将通知强制显示为“悬浮式通知”。不幸的是,这也无效。
onMessageReceived
的代码。很可能是由于onMessageReceived
中的某些条件,导致sendNotification
没有被调用。 - Ranjan