android - 通过单击通知调用 Firebase onMessageReceived

标签 android firebase firebase-notifications

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

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

最佳答案

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

关于android - 通过单击通知调用 Firebase onMessageReceived,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38625331/

相关文章:

android - 在 Android 上将 JSON 从 String 加载到 JSONArray

Android:如何在不重写重写方法的情况下在每个(列表) Activity 中都有一个共享菜单?

firebase - 用于编制索引的 Cloud Firestore 通配符

android - 使用 FCM 时的通知跟踪

java - 当我按下连续按钮时,为什么它不连续运行?

android - 移动应用程序的本地化 - 是否有可用于基础知识的资源?

android - 基于 Firebase 控制台的通知中消息文本的字符限制是多少?

android - 通知从 firebase 控制台发送但显示失败状态但发送到所有设备被标记为已完成

Android GPS定位问题

ios - 函数应该将用户添加到 Firebase 中其他 friend 节点的列表中,但它返回 nil