android - Firebase onMessageReceived(RemoteMessage remoteMessage),当应用程序处于后台时不会被调用

标签 android firebase firebase-cloud-messaging

<分区>

在 Firebase onMessageReceived(RemoteMessage remoteMessage) 中,当您的应用程序处于前台时将调用此方法。因此,在单击通知时,您可以打开一个不同的 Activity ,比如 NotiicationActivity

但是如果你的应用程序在后台,那么这个方法将不会被调用,并且在点击通知时只会打开一个 Launcher Activity。

那么即使我们的应用程序处于后台,如何在单击通知时打开 NotificationActivity

我的代码是这样的:

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

最佳答案

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

所以我的建议是, 在接收 Activity 中,您仍然可以使用以下方法从通知中获取数据:

getIntent().getExtras();

这应该会相应地工作。希望这会有所帮助:)

关于android - Firebase onMessageReceived(RemoteMessage remoteMessage),当应用程序处于后台时不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41009936/

相关文章:

java - 在 Android Studio 中禁用后如何启用检查?

android - OkHttp Request 返回缓存结果,用于不同的 X Auth Tokens

javascript - JS构造函数看不到变量

ios - 如何在 Firebase 中将项目更新/添加到 JSON 数组?

android - java.lang.NullPointerException : at com. 谷歌.firebase.iid.zzad.zzchp

android - Firebase 推送通知与 childAdd 监听器

android - 如何在已安装的 .apk 上运行 monkeyrunner

安卓布局问题

java - 如何在 firestore android studio 中排序或排序?

sqlite - pod 'FirebaseMessaging' 更新后找不到“sqlite3.h”文件