【发布时间】:2018-07-10 06:25:03
【问题描述】:
我正在使用 Firebase 向我的应用发送推送通知。我的应用支持到 API 级别 27。我正在使用 FirebaseMessagingService 接收通知。在 onMessageReceived() 方法中,我正在获取数据有效负载并在托盘中创建自己的通知。从控制台我只发送数据有效负载,因为如果应用程序在后台,我不希望应用程序创建系统通知。现在,当应用程序处于前台和后台时,我可以在 onMessageReceived() 中获得回调。但问题是当应用程序从内存中清除(或被杀死)时它没有被调用。当我的应用程序被杀死时,如何在 onMessageReceived 中获得回调?
Manifest.xml
<service android:name=".service.MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".service.FcmMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="promotions" />
FCMessagingService.java
public class FcmMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Logger.v(Logger.TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Logger.v(Logger.TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
//JSONObject json = new JSONObject(remoteMessage.getData().toString());
NotificationHandler.handleNotification(this, formNotificationObject(null));
} catch (Exception e) {
Logger.e(Logger.TAG, "Exception: " + e.getMessage());
}
}
}
private Notification formNotificationObject(JSONObject data) {
//creating notifcation object here
}
build.gradle
compile "com.google.firebase:firebase-messaging:11.4.2"
compile 'com.facebook.android:facebook-android-sdk:4.29.0'
compile "com.android.support:appcompat-v7:26.0.0"
有效载荷
{
"to": "cogzTKfWsXI:APA9................plSjNu",
"mutable_content": false,
"time_to_live": 20,
"data": {
"messageid": 10,
"title": "Test",
"body": "Testing",
"image": "",
"expiry": "2018-11-13 11:35:11"
}
}
【问题讨论】:
-
您在哪个设备上测试?
-
我认为
onMessageReceived不应该在应用被杀死时被调用,因为它是你应用中的代码并且你的应用被杀死 -
@sandeepkolhal 我正在测试一加五 Oxygen OS 5.0,奥利奥。
-
你在其他手机上测试过吗?试试这个stackoverflow.com/questions/36035284/…
-
@sandeepkolhal 我只在一加五中进行测试,因为这是这里唯一可用的带有奥利奥操作系统的设备。
标签: android firebase push-notification firebase-cloud-messaging