我正在使用firebase消息服务向我的android应用程序获取通知,但该服务只调用了一次!如何处理它,让它在我收到消息时被调用?这是我的代码:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String user_id = "0";
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
user_id = remoteMessage.getData().get("from_user");
}
String click_action = remoteMessage.getNotification().getClickAction();
Log.d(TAG, "Message data payload: " + click_action);
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle(), user_id, click_action);
}
private void sendNotification(String messageBody, String messageTitle, String user_id, String click_action) {
Intent intent = new Intent(click_action);
intent.putExtra("user_id", user_id);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
还有我的有效载荷:
const payload = {
notification: {
title: "New Friend Request",
body: `${userName} has sent you a Friend Request`,
icon: "default",
click_action: "com.example.alaa.lapitchatapp.Target_Notification"
},
data:{
from_user: from_user_id
}
};
这是Mainfest:中的服务
<service android:name=".FirebaseMessagingService">
<intent-filter>
<action
android:name=
"com.google.firebase.MESSAGING_EVENT"
/>
</intent-filter>
</service>
当您的应用程序处于后台或为解决此问题而终止时,您发送通知的方式onMessageReceived()
将不会被调用在发送通知时删除通知字段,并仅发送类似的数据
{
data:{
from_user: from_user_id
// you can add more field if you want
}
};
在您的通知请求中包括提交的"priority": "high"
,以便您尽快收到通知以了解更多详细信息。请查看此答案
经过太多的挖掘,我意识到
通知将发送到设备的系统托盘,数据有效载荷将在我的启动器活动的附加部分中发送
所以我应该处理我发送通知的活动中的额外内容。答案在这里
因此,不需要在onMessageReceived((中编写任何代码。
谢谢大家。真的很感激