Store token for FCM

2019-06-07 22:57发布

I am trying to store my token in my cloud DB. I am going to use this token later in a cloud function in order to send a notification to a user that has been added as a friend.

Pushing the device token however does not work because the user is unauthorized. I can't save it after they are authorized because the token is generated when the app is installed.

 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条回答
祖国的老花朵
2楼-- · 2019-06-07 23:57

Save the token in SharedPreferences, after a successful login save the token to Firebase database, keep in mind that if you remove the app cache or reinstall the app the token is always different

查看更多
登录 后发表回答