How to handle FirebaseInstanceId.getInstance().get

2019-01-17 16:17发布

问题:

I have just migrated to FCM. I have added my class that extends from FirebaseInstanceIdService to receive a refreshedToken as and when appropriate.

My question is specific to the case when user installs my app first time and due to some reason, unable to receive a registration Id from onTokenRefresh. How are we supposed to handle this? Can I set a broadcast receiver from my FirebaseInstanceIdService class which will notify the Main activity when a registration Id is received?

回答1:

  • if your device have no connection to the internet onTokenRefresh() is never called and you should notify to user his/her device has no internet connection
  • firebase has its own network change listener and when a device connected to the internet then try to get token and return it, at this time you can tell your main activity by sending a local broadcast receiver that registration token is received.

use below codes:

    @Override
public void onTokenRefresh() {

    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    Log.d("FCN TOKEN GET", "Refreshed token: " + refreshedToken);

    final Intent intent = new Intent("tokenReceiver");
    // You can also include some extra data.
    final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
    intent.putExtra("token",refreshedToken);
    broadcastManager.sendBroadcast(intent);


}

in your main activity:

    public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
   LocalBroadcastManager.getInstance(this).registerReceiver(tokenReceiver,
            new IntentFilter("tokenReceiver"));

}

BroadcastReceiver tokenReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String token = intent.getStringExtra("token");
        if(token != null)
        {
            //send token to your server or what you want to do
        }

    }
};

}


回答2:

As far as I know, token will be null only when you try to run your app on emulator on which google play service is not there and when you are using dual email id on you google play store(on you actual device), but only one email id is verified for the usage. Those are the cases which will give you null token and I have already implemented FCM in my new project. So for rest of any cases , token won't be null.



回答3:

Change this in manifest.xml file tools:node="replace" to tools:node="merge".



回答4:

I was facing the same problem. I looked through a lot of SO posts and other forums and I found a solution that worked for me. FCM documentation says to use this method to get a token.

String refreshedToken = FirebaseInstanceId.getInstance().getToken();

I found a post online (I apologize, I don't remember which one. I found it a while ago) that used this method instead:

String refreshedToken = FirebaseInstanceId.getInstance().getToken() (String authorizedEntity, String scope);

FCM documentation describes the first method as:

Return the master token for the default Firebase project.

While the second one is described as:

Returns a token that authorizes an Entity to perform an action on behalf of the application identified by Instance ID. This is similar to an OAuth2 token except, it applies to the application instance instead of a user. For example, to get a token that can be used to send messages to an application via FirebaseMessaging, set to the sender ID, and set to "FCM".

I have been looking into why the first method call takes a longer time to return a token, but I haven't found an answer yet. Hope this helps.



回答5:

depending on your application logic you can write the code to handle the "new" token directly in the FirebaseInstanceIdService.onTokenRefresh() method, or you can use a LocalBroadcast to send this information to your activity if you need to change the UI when this event happens.

Note that when onTokenRefresh() is called your activity could be closed.

A possible implementation could a mix of the two options:

  1. add some logic in onTokenRefresh() to send the token to your server
  2. use a LocalBroadcastReceiver to inform your activity, if you have a piece of UI that need to change when the token is available.


回答6:

Use this class extends with..

public class MyFirebaseInstanceIDService  extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";
    public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";


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

        Toast.makeText(MyFirebaseInstanceIDService.this,refreshedToken,Toast.LENGTH_LONG).show();
    }
}


回答7:

If you are running it on your emulator, check that you have Google play services enabled in Tools -> Android -> SDK Manager -> SDK Tools -> Google play services

Once installed, reboot both Android Studio and your emulator

It worked for me