当前位置: 首页 > 知识库问答 >
问题:

Firebase onMessageReceived(RemoteMessage RemoteMessage),当应用程序位于后台时不调用[重复]

刘玉石
2023-03-14

我的代码是这样的:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        sendNotification(remoteMessage.getNotification().getBody());

    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, NewActivity.class);
        intent.putExtra("key", messageBody);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
        Bitmap icon2 = BitmapFactory.decodeResource(getResources(),
            R.mipmap.ic_launcher);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("FCM Sample")
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setLargeIcon(icon2)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(new Random().nextInt() /* ID of notification */, notificationBuilder.build());
    }
}

共有1个答案

楚浩然
2023-03-14

onMessageReceived仅在应用程序处于前台时触发。如果应用程序是后台的,您可能仍然能够收到通知,但不会触发onMessageReceived。

所以我的建议是,在接收活动上,您仍然可以通过使用:

getIntent().getExtras();

这应该会相应地起作用。希望这有帮助:)

 类似资料: