gpt4 book ai didi

android - 当应用程序处于前台时如何处理 Firebase 通知

转载 作者:IT老高 更新时间:2023-10-28 23:08:53 30 4
gpt4 key购买 nike

我已将 Firebase 云消息传递与我的应用程序集成。当我从 Firebase 控制台发送通知时,如果应用程序在后台或未打开,我会成功收到通知,否则,如果应用程序在前台或已打开,我没有收到它。

感谢所有建议。

最佳答案

当应用在前台时,通知不会自己生成。您需要编写一些额外的代码。收到消息时,会调用 onMessageReceived() 方法,您可以在其中生成通知。代码如下:

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());
}
}

关于android - 当应用程序处于前台时如何处理 Firebase 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38451235/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com