How to launch FCM ID Service only after a particular activity is triggered?

Assume I have a LoginActivity where user can either register or login with existing credentials. I don't want FirebaseInstanceIdService to generate a token, unless user is logged in and MainActivity of the application is launched.

Thank you


ANSWERS:


You cannot block FirebaseInstanceIdService.onTokenRefresh() from being called until the user is logged in.

What you could do in your use case is:

  • In FirebaseInstanceIdService.onTokenRefresh() ignore the event if the user is not logged-in
  • When the user log-in check FirebaseInstanceId.getToken() and if != null call onTokenRefresh() (or directly your logic) manually.

In this way you can process the token when the user is logged-in, and if the token is not available (or is rotated) you will receive the onTokenRefresh() event later.

Update (July 3 2017): in the comments a reader reminded that FirebaseInstanceIdService.onTokenRefresh() could be called after the user log in.

This is right. When the user log in, getToken() could still return null if onTokenRefresh() has not been called earlier.

You need to hadle this case in your app. Most likely the user can use the app anyway, but you cannot send a push notification until you received the token.

When onTokenRefresh() is finally called, if the user log in before, than you can associate the token the user.


Sorry but that is not possible. FirebaseInstanceIdService call automatically on application startup and generate a Token. Keep in mind that its related with application Instance. Not with the one particular user. If you are trying to save Token with one particular user (i.e when user logged in then you will save that token in server db for push notification of that user).If you are doing this a bug you will faced in future is that if Two user share one application Instance then push notification may be pushed to wrong user .. Hope you get my point.


I am maintaining one flag in shared pref which indicates whether gcm token sent to server or not. In Splash screen every time I am calling one method sendDevicetokenToServer. This method checks if user id is not empty and gcm send status then send token to server.

   public static void  sendRegistrationToServer(final Context context) {

    if(Common.getBooleanPerf(context,Constants.isTokenSentToServer,false) ||
            Common.getStringPref(context,Constants.userId,"").isEmpty()){

        return;
    }

    String token =  FirebaseInstanceId.getInstance().getToken();
    String userId = Common.getUserId(context);
    if(!userId.isEmpty()) {
        HashMap<String, Object> reqJson = new HashMap<>();
        reqJson.put("deviceToken", token);
        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<JsonElement> call = apiService.updateDeviceToken(reqJson,Common.getUserId(context),Common.getAccessToken(context));
        call.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> serverResponse) {

                try {
                    JsonElement jsonElement = serverResponse.body();
                    JSONObject response = new JSONObject(jsonElement.toString());
                    if(context == null ){
                        return;
                    }
                    if(response.getString(Constants.statusCode).equalsIgnoreCase(Constants.responseStatusSuccess)) {

                        Common.saveBooleanPref(context,Constants.isTokenSentToServer,true);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable throwable) {

                Log.d("", "RetroFit2.0 :getAppVersion: " + "eroorrrrrrrrrrrr");
                Log.e("eroooooooorr", throwable.toString());
            }
        });

    }

}

In MyFirebaseInstanceIDService class

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

    // 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.
    Common.saveBooleanPref(this,Constants.isTokenSentToServer,false);
    Common.sendRegistrationToServer(this);

}


 MORE:


 ? Service is being started but OnCreate or OnStart are not being called
 ? Firebase Android Authentication failed: expired_token (Auth token is expired)
 ? when does an android gcm token expire
 ? FCM Token Issue in some android device
 ? FCM - onTokenRefresh() is never called
 ? Does firebase manage user data like device token, bundle id etc at their own when sending push notifications or we have to manage these data?
 ? Firebase FCM token - When to send to server?
 ? FCM - onTokenRefresh() is never called
 ? onTokenRefresh not getting called in signed APK, if previous version of app installed doesn't have FCM implemented
 ? FCM onTokenRefresh() sometimes not called