【问题标题】:Firebase Notifications integration onTokenRefresh not getting calledFirebase 通知集成 onTokenRefresh 没有被调用
【发布时间】:2018-01-11 16:37:13
【问题描述】:

我正在尝试启用 Firebase 通知,但似乎无法正常工作。

如果觉得我在这里错过了一步,但我不确定是什么。

我已在同一个应用程序中集成了 firebase auth 和 firebase 数据库,并且两者都按预期工作。

我在我的 android 清单中添加了 2 个服务:

<service
    android:name="tld.domain.app.lib.firebase.MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

<service
    android:name="tld.domain.app.lib.firebase.MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

我可以按住 Ctrl 键并单击类,以便将名称指向正确的位置。

我还给类的onTokenRefresh方法加了一个断点:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        Log.d(TAG, "sendRegistrationToServer: " + token);

        // TODO: Implement this method to send token to your app server.
    }

}

为什么不调用它?我在这里错过了什么?

【问题讨论】:

    标签: android firebase firebase-cloud-messaging


    【解决方案1】:

    只有在刷新令牌时才会触发/调用此接收器。对于初始注册,您需要显式调用注册方法。

    应用需要调用下面的方法来获取推送令牌。 Token不会自行生成

    FirebaseInstanceId.getInstance().getToken()
    

    请参阅official example 了解更多详情。确切代码snippet

    【讨论】:

    • 这个答案正好相反:stackoverflow.com/questions/37451395/…我应该如何调用注册方法?你能说得更具体点吗?
    • 更新了答案,答案对于firebase库的初始版本是正确的,现在机制已经改变了。 git repo 共享由 firebase 团队维护,您可以参考它以获得最佳实践和指导。
    • 我必须卸载应用并重新安装才能触发 onTokenRefresh。显然令牌已经生成,我只需要从我的代码中的任何地方调用你上面提到的代码,所以我会将你的标记为答案。
    猜你喜欢
    • 2016-09-23
    • 2016-09-24
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2012-01-08
    相关资源
    最近更新 更多