如果应用程序在后台,则不会触发OnMessageReceived

时间:2017-06-09 09:37:52

标签: android firebase push-notification firebase-cloud-messaging

我一直在开发Android应用程序,所有这些应用程序都集成了FCM并且运行正常。

我有这个应用程序,除非打开应用程序,否则不会触发onMessageReceived,如果应用程序已关闭并且我收到通知,它会从启动时打开并遵循正常流程(它不会转到通知活动) 。 N.B:我所做的所有测试都来自Firebase控制台

我真的不知道为什么,任何帮助都会受到赞赏。

这是我的代码:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.wtf("RECEIVED","NOTIFICATION");

    // TODO(developer): Handle FCM messages here. 
    Log.wtf(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.wtf(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.wtf(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }


    sendNotification("Notification");
}

private void sendNotification(String messageBody) {


    Intent intent = new Intent(this, HomeActivity.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

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

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

1 个答案:

答案 0 :(得分:2)

使用 Firebase ,您可以基本上发送两种类型的通知消息。

<强> 1。通知消息:有时被视为&#34;显示消息。&#34;

<强> 2。数据/有效载荷消息:由客户端应用程序处理。

以上两种通知都有不同的行为,具体取决于您的应用是在前台还是后台。

1.Notification msg + Background :已发送到通知托盘

2.Notification msg + Foreground :Android上的onMessageReceived()

3.Data msg + Background :应用程序在通知托盘中接收通知有效内容,并仅在用户点击通知时处理数据有效负载。

4.Data msg + Foreground :您的应用会收到两个有效负载的消息对象。

有关更多说明check this.

使用FCM控制台发送数据/有效负载消息时,使用“高级”选项并插入键和值。

enter image description here

相关问题