After integrating Firebase Cloud Messaging, the app sometimes crashed during its first two minutes. The log showed:
1
2
| Fetching FCM registration token failed
java.io.IOException: java.util.concurrent.ExecutionException: java.io.IOException: SERVICE_NOT_AVAILABLE
|

First verify Google Play Services availability:
1
2
3
4
| public static boolean supportsGoogleServices(Context context) {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
return api.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS;
}
|
Dependency:
1
| implementation 'com.google.Android.gms:play-services-base:18.5.0'
|
The service may also be unavailable because of the device’s network environment. More importantly, do not call task.getResult() after a failed task. Return immediately or handle the exception:
1
2
3
4
5
6
7
8
9
10
| FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
myFCMtoken = null;
return;
}
myFCMtoken = task.getResult();
Log.d(TAG, "FCM Token: " + myFCMtoken);
});
|
After guarding the failed result and uninitialized token, the crashes stopped.