gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:42:09 28 4
gpt4 key购买 nike

当应用程序通过点击通知处于前台或后台时,应用程序调用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com