为FCM存储令牌

时间:2017-11-21 00:02:58

标签: android google-app-engine firebase firebase-cloud-messaging

我正在尝试将令牌存储在我的云端DB中。我稍后将在云功能中使用此令牌,以便向已添加为朋友的用户发送通知。

但是,推送设备令牌不起作用,因为用户未经授权。我无法在授权后保存它,因为在安装应用程序时会生成令牌。

 private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }

    /**
     * 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) {
        // Add custom implementation, as needed.
        FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference deviceToken = mFirebaseDatabase.getReference("device_token");
        deviceToken.push().setValue(token).addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                Log.i("token push","Success!");
            } else {
                Log.i("token push","Failed !");
            }
        });
    }

1 个答案:

答案 0 :(得分:2)

将令牌保存在SharedPreferences中,成功登录后将令牌保存到Firebase数据库,请记住,如果删除应用缓存或重新安装应用,则令牌总是不同