现在我知道,如果我发送数据消息,即使应用程序在后台,通知也会出现。但即使在发送数据消息后,我也没有收到任何通知。
我正在使用Postman进行测试,这是我的邮递员请求的主体:
{
"to" : (device token),
"data" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"content_available" : true,
"priority" : "high",
"sound": "default",
"time_to_live":"2419200"
}
}
这是我的onMessageReceived()
功能:
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String,String> data=remoteMessage.getData();
String title=data.get("title");
String body=data.get("body");
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
sendPushNotification(title,body);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
这就是我的sendPushNotification()
函数的样子:
private void sendPushNotification(String title,String message) {
try {
String imageUrl="";
MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
if(imageUrl.equals("null")){
mNotificationManager.showSmallNotification(title, message, intent);
mNotificationManager.playNotificationSound();
}else{
mNotificationManager.showBigNotification(title, message, imageUrl, intent);
mNotificationManager.playNotificationSound();
}
} catch (Exception e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
}
}
我正在关注堆栈溢出问题:How to handle notification when app in background in Firebase
P.S。:当应用程序在前台时,通知正在接收正常。
答案 0 :(得分:2)
正如您在我的帖子中看到的,对于特定ID,您应该使用"registration_ids": ["{device-token}","{device2-token}","{device3-token}"]
键和值而不是”to”
。这是主题
答案 1 :(得分:1)
您需要在通知有效内容中定义click_action
。
"notification"{
"click_action":"YOUR_ACTIVITY_NAME"
}
也在您的清单中编辑活动定义,如下所示
<activity
android:name="com.demo.xyzActivity"
android:windowSoftInputMode="stateHidden">
<intent-filter>
<action android:name=".xyzActivity" /> //This should be one set into payload
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
当app在后台时,这将打开您的活动。
答案 2 :(得分:0)
您使用通知有效负载和数据有效负载吗?因为该函数找到通知有效负载,它将其直接发送到通知托盘,因此忽略了数据有效负载。 改变
JSONObject json = new JSONObject(remoteMessage.getData().toString());
到
Map<String, String> bundleData = remoteMessage.getData();
这会删除try catch,并会在导致异常时通知你。
答案 3 :(得分:0)
创建BroadcastReceiver
在Manifest.xml中声明
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver
android:name=".OnBootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
创建OnBootBroadcastReceiver.java文件并在其中调用FCM服务。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class OnBootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent("com.example.FirebaseMessagingReceiveService");
i.setClass(context, FirebaseMessagingReceiveService.class);
context.startService(i);
}
}