Store token for FCM

坚强是说给别人听的谎言 提交于 2019-12-23 01:21:39

问题


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:


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



来源:https://stackoverflow.com/questions/47403162/store-token-for-fcm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!