我已将 Firebase 云消息传递与我的应用程序集成.当我从 Firebase 控制台发送通知时,如果应用程序在后台或未打开,我会成功收到通知,否则,如果应用程序在前台或已打开,我没有收到它.
I have integrated Firebase Cloud Messaging with my application. When I sent a notification from the Firebase console, if the app is in background or not opened I receive successfully the notification, otherwise if the app is in foreground or opened, I did not receive it.
感谢所有建议.
应用在前台时,不会自己生成通知.您需要编写一些额外的代码.收到消息时,会调用 onMessageReceived()
方法,您可以在其中生成通知.代码如下:
When app is in foreground, notifications are not generated themselves. You need to write some additional code. When message is received onMessageReceived()
method is called where you can generate the notification. Here is the code:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}
这篇关于当应用程序处于前台时如何处理 Firebase 通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!