Update Firebase Instance ID on app update

2019-05-01 19:16发布

Back in the GCM days it was recommended that every time you put out an update to your app you should check to see if a new registration id was given (since it is was not guaranteed to be the same after an update) when the app starts.

Is that still the case with FCM? I couldn't find any documentation about this

2条回答
SAY GOODBYE
2楼-- · 2019-05-01 19:48

You should check both the current token when your app runs and monitor onTokenRefresh() to detect when the token changes.

Check the current token on app/main activity startup by calling FirebaseInstanceID.getToken():

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        String token = FirebaseInstanceId.getInstance().getToken();
        if (token != null) {
            sendRegistrationToServer(refreshedToken);
        }
    }
    ...

The sendRegistrationToServer() method that is called in this snippet is something you implement to send the registration token to your own server (or a serverless solution like the Firebase Database).

Monitor for changes to the token by subclassing an FirebaseInstanceIdService and overriding onTokenRefresh():

@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    // 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);
}

See the documentation here: https://firebase.google.com/docs/cloud-messaging/android/client#sample-register

查看更多
劫难
3楼-- · 2019-05-01 19:56

You do not need to check whether the token was lastest. The method onTokenRefresh() always called if a new token was generated.

What you need to do is that checking your token was sent to your server when the onTokenRefresh() was called.

查看更多
登录 后发表回答