1

当应用程序通过单击通知处于前台或后台时,应用程序会调用 onMessageReceived 事件。我使用 click_action 通知。对吗?

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

4

2 回答 2

2

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

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

我们可以在这个 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());
}
}
于 2016-07-28T03:16:12.927 回答
2

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

  • 数据消息总是导致 onMessageReceived 被调用
  • 应用程序在前台时的通知消息导致 onMessageReceived 被调用

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

在此处查看有关这两种 FCM 消息的更多信息。

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

于 2016-07-29T00:35:56.847 回答