Android开发:如何兼容不同版本的Google Play Services API?
兼容Google Play Services废弃API的实现方案
处理Android系统API的废弃兼容很直观——就像你举的SoundPool例子,直接通过Build.VERSION.SDK_INT判断系统版本就能搞定:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mTonePlayer = new SoundPool.Builder().build(); } else { mTonePlayer = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); }
但Google Play Services的API废弃逻辑完全不同:它不依赖Android系统版本,只看设备上安装的Play服务版本号。比如你提到的LocationServices.GeofencingApi在Play服务11.0.0之后被GeofencingClient取代,这时候就得换一套检测和兼容逻辑。
核心思路:检测Play服务版本
我们需要先获取设备上当前运行的Google Play Services版本号,再根据版本判断使用旧API还是新API。这里可以用GoogleApiAvailability类来获取版本号,11.0.0对应的整数版本代码是11000000(格式为主版本号*1000000 + 次版本号*10000 + 修订号*100)。
完整兼容代码示例
第一步:确保依赖到位
先确认你的build.gradle模块文件中包含了Play服务定位组件的依赖(建议使用能覆盖11.0.0及以上的版本):
implementation 'com.google.android.gms:play-services-location:21.0.1'
第二步:Java兼容代码
// 获取设备上的Play服务版本号 int playServicesVersion = GoogleApiAvailability.getInstance().getApkVersion(context); // 11.0.0对应的版本代码是11000000 if (playServicesVersion < 11000000) { // 旧版本:使用GeofencingApi if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, yourPendingIntent) .setResultCallback(status -> { // 处理移除结果 if (status.isSuccess()) { // 移除成功逻辑 } else { // 移除失败逻辑 } }); } } else { // 新版本:使用GeofencingClient GeofencingClient geofencingClient = LocationServices.getGeofencingClient(context); geofencingClient.removeGeofences(yourPendingIntent) .addOnSuccessListener(aVoid -> { // 移除成功逻辑 }) .addOnFailureListener(e -> { // 移除失败逻辑,比如打印异常信息 e.printStackTrace(); }); }
第三步:额外注意事项
- 提前检查Play服务可用性:在调用上述代码之前,建议先检查设备是否安装了可用的Play服务,避免崩溃:
int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context); if (resultCode != ConnectionResult.SUCCESS) { // 提示用户更新或安装Play服务 GoogleApiAvailability.getInstance().getErrorDialog(activity, resultCode, 0).show(); return; } - GoogleApiClient的兼容:旧版本API依赖
GoogleApiClient,你需要保留它的初始化和连接逻辑;新版本则不需要,直接使用GeofencingClient即可。
Kotlin版本参考
如果你的项目用Kotlin,兼容代码可以这样写:
val playServicesVersion = GoogleApiAvailability.getInstance().apkVersion if (playServicesVersion < 11000000) { mGoogleApiClient?.takeIf { it.isConnected }?.let { client -> LocationServices.GeofencingApi.removeGeofences(client, yourPendingIntent) .setResultCallback { status -> when { status.isSuccess -> { /* 移除成功 */ } else -> { /* 移除失败 */ } } } } } else { val geofencingClient = LocationServices.getGeofencingClient(context) geofencingClient.removeGeofences(yourPendingIntent) .addOnSuccessListener { /* 移除成功 */ } .addOnFailureListener { e -> e.printStackTrace() } }
内容的提问来源于stack exchange,提问作者Simon Hutton
相关产品推荐
相关产品推荐

