问题
What I Have
I have an app that heavily relies on Google Play Services (for Firebase), so I need the user's device to have Play Services installed. More importantly, the Play Services version installed in the device should be equal to or higher than the Play Services I am using in my app.
What I Want
I want to show a message (maybe a dialog or snackbar) in the Splash screen of my app if the user is using an old Play Services version that the version I am targeting in my app.
Like currently, the version of Play Services I am using in my app is 10.0.1. This is the version name obviously.
I know I can do this,
int v = getPackageManager().getPackageInfo("com.google.android.gms", 0 ).versionName;
But I am unable to compare the versions of the Play Services installed in the device and the Play Services I am using? Should I be doing it using the versionCode instead of the versionName? If so, how do I know the versionCode of the Play Services I am using?
Or is there a different (or better) way to do this?
回答1:
This is method i use .. cheers
public static boolean checkPlayServices(Context context) {
final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int resultCode = api.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
if (api.isUserResolvableError(resultCode))
api.getErrorDialog(((Activity) context), resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
else {
showToast(context, "This device is not supported.", true);
((Activity) context).finish();
}
return false;
}
return true;
}
回答2:
Usman's answer is good, additionally you can call GoogleApiAvailability.makeGooglePlayServicesAvailable() in the event of a non-successful result code. Like this:
int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this);
}
Further details about result codes, etc. available in docs here: https://developers.google.com/android/reference/com/google/android/gms/common/GoogleApiAvailability
来源:https://stackoverflow.com/questions/42005217/detecting-play-services-installed-and-play-services-used-in-app