通过单击通知来调用Firebase onMessageReceived

时间:2016-07-28 00:35:18

标签: android firebase firebase-notifications

当应用程序位于前台或后台时,通过单击通知,应用程序将调用onMessageReceived事件。我使用click_action通知。这是正确的吗?

我在应用程序处于前台时创建通知,当我点击通知时,它再次执行该方法并创建另一个通知。

2 个答案:

答案 0 :(得分:2)

onMessageReceived是一个在Android客户端从Firebase Cloud收到消息时调用的方法。通常,我们创建一个函数来在此方法中构建通知。

当我们点击通知时会发生什么,我们可以使用pendingIntent。

我们可以在this github repo

中看到Google中的示例
public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {


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

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

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

    // Also if you intend on generating your own notifications as a result of a received FCM
    sendNotification(remoteMessage.getNotification().getBody());
}
// [END receive_message]

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.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.drawable.ic_stat_ic_notification)
            .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 :(得分:2)

是否调用onMessageReceived取决于以下几点:

  • 数据消息始终会导致onMessageReceived被调用
  • 当应用程序位于前台时的通知消息导致onMessageReceived被调用

当您的应用在后台并发送通知消息时,会显示自动生成的通知。

详细了解两种类型的FCM消息here

click_action可用于指定当用户点击自动生成的通知时启动哪个Activity,如果未指定则启动默认活动。 click_action目前仅通过REST API提供。