我正在使用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>
答案 0 :(得分:0)
您的onMessageReceived()
发送通知的方式不会在您的应用处于后台或被终止以解决此问题的情况下被调用,删除通知字段同时发送通知并仅发送此类数据
{
data:{
from_user: from_user_id
// you can add more field if you want
}
};
在您的通知请求中包括"priority": "high"
,以便您尽快获得通知,请检查此answer
答案 1 :(得分:0)
经过太多的挖掘,我意识到
通知将发送到设备的系统托盘,数据有效载荷将在启动器活动的意图范围内发送。
因此,我应该处理将通知发送到的活动中的其他内容。答案在here
中因此,无需在onMessageReceived()内部编写任何代码。
感谢大家。真的很感激