Firebase FCM token - When to send to server?

后端 未结 4 813
眼角桃花
眼角桃花 2020-12-31 04:19

Okay so I have an app which on first start takes you through a few welcoming slides, then takes you to a login/register page and then to MainActivity.

I

4条回答
  •  情书的邮戳
    2020-12-31 04:20

    Yes FCM token is generated automatically. But try to see this in a different angle.

    This is how I handled it.

    Let FCM generate token as soon as your app starts. OnTokenRefresh will be called and you just save it in your preferences as:

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
    
        sendRegistrationToServer(refreshedToken);
    }
    
    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
        SharedPreferenceUtils.getInstance(this).setValue(getString(R.string.firebase_cloud_messaging_token), token);
        
       // To implement: Only if user is registered, i.e. UserId is available in preference, update token on server.
       int userId = SharedPreferenceUtils.getInstance(this).getIntValue(getString(R.string.user_id), 0);
       if(userId != 0){
           // Implement code to update registration token to server
       }
    }
    

    Hope you are clear with the way. Ask if you need more clearance on it.

    Edit

    Using the new Firebase SDK (21.0.0) , you need to override onNewToken() method instead of onTokenRefresh()

     @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        sendRegistrationToServer(s);
    }
    

提交回复
热议问题