应用程序在前台时如何处理Firebase通知 [英] How to handle the Firebase notification when app is in foreground

查看:205
本文介绍了应用程序在前台时如何处理Firebase通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将Firebase Cloud Messaging与我的应用程序集成在一起. 当我从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.

所有建议,我们感激不尽.

All suggestions are appreciated.

推荐答案

当应用程序处于前台状态时,不会自行生成通知.您需要编写一些其他代码.收到消息后,将调用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通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆