应用程序在前台时如何处理 Firebase 通知

How to handle the Firebase notification when app is in foreground

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

FirebaseMessagingService 当应用程序处于前台时永远不会工作。在这种情况下,如果您想接收来自 FCM 的消息,那么 WakefulBroadcastReceiver 将为您工作

public class FirebaseDataReceiver extends WakefulBroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d("BroadcastReceiver::", "BroadcastReceiver");
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(intent.getExtras().getString("title"))
                    .setContentText(intent.getExtras().getString("message"));
            NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            manager.notify(0, builder.build());
        }
    }

Link firebaseGCM 在 play store 中并在清单

中写入以下代码
<receiver
    android:name=".firebase.FirebaseDataReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</receiver>