FCM token returns null in android nougat

2019-09-20 00:51发布

问题:

FCM token not generated in Android Nougat device(Moto,Sony & Huawei) when installed my app FirebaseInstanceId.getInstance().getToken() returns null, But FCM token generated in Emulator(Nougat) and below Nougat versions.

回答1:

When do you call FirebaseInstanceId.getInstance().getToken()? You need to wait in a Service extending FirebaseInstanceIdService for the onTokenRefresh callback. This is the moment, where your Token is available.

public class FcmTokenService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
    try {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        if (refreshedToken != null) {
            Log.i("FCM", String.format("Received new registration token from Firebase: token=\"%s\";", refreshedToken));
            // ... forward the new token to some point in your app to store it
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Register the service in your manifest:

    <service android:name=".services.FcmTokenService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

And this should be the last line in your build.gradle file:

apply plugin: 'com.google.gms.google-services'