【问题标题】:FirebaseMessagingService not called after second background在第二个背景后未调用 FirebaseMessagingService
【发布时间】:2017-02-14 06:12:38
【问题描述】:

我尝试将 Firebase 用于 Android 推送通知。但我遇到了非常奇怪的问题。当我在前台发送推送时一切正常。当我在后台发送推送时一切正常(我只发送数据),直到我回到前台然后回到后台。

当我的应用第二次进入后台时,不会调用我的 FirebaseMessagingService。另外,请注意我使用的是 Android 模拟器。代码:

public class MyAndroidFirebaseMsgService extends FirebaseMessagingService {
    private static final String TAG = "MyAndroidFCMService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
    }
}

//... 

public class MyAndroidFirebaseInstanceIdService extends FirebaseInstanceIdService {

    private static final String TAG = "MyAndroidFCMIIDService";

    @Override
    public void onTokenRefresh() {
        //Get hold of the registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        //Log the token
        Log.d(TAG, "Refreshed token: " + refreshedToken);
    }
    private void sendRegistrationToServer(String token) {
        //Implement this method if you want to store the token on your server
    }
}

AndroidManifest.xml:

<service android:name=".MyAndroidFirebaseMsgService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".MyAndroidFirebaseInstanceIdService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

服务器:

curl -H "Content-type: application/json" -H "Authorization:key=<MYKEY>"  -X POST -d '{"to": "<MYTOKEN>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send

我该如何解决?

【问题讨论】:

    标签: android firebase android-service android-notifications firebase-cloud-messaging


    【解决方案1】:

    这是按预期工作的,只有当您的应用程序处于前台时,通知消息才会传递到您的 onMessageReceived 回调。如果您的应用处于后台或已关闭,则通知中心会显示一条通知消息,并且该消息中的任何数据都会传递给由于用户点击通知而启动的 Intent。

    您可以指定 click_action 来指示用户点击通知时应启动的意图。如果未指定 click_action,则使用主要活动。

    Intent 启动后,您可以使用

    getIntent().getExtras(); 检索一个包含随通知消息一起发送的任何数据的 Set。

    更多关于通知消息https://firebase.google.com/docs/cloud-messaging/android/receive#sample-receive

    【讨论】:

    • FirebaseMessagingService 不会在后台调用
    • if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { Object value = getIntent().getExtras() .get(key); Log.d("MainActivity:", "Key:" + key +" Value:" + value); } }
    • 可以从intent对象获取数据
    • 嗯...感谢您的回复,但您确定您正确理解了我的问题吗?
    • 我面临同样的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多