You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

compileSdkVersion 32下,如何为API 31以下版本创建LocationRequest?

适配API 31以下版本创建LocationRequest的方案

有两种可靠的方式解决这个兼容问题:

1. 原生版本判断+抑制废弃警告

直接通过系统版本号分支处理,在API 31及以上使用LocationRequest.Builder,低版本调用已废弃的LocationRequest.create(),同时用注解忽略编译警告(compileSdk 32会标记该方法为废弃,但低版本设备仍可正常运行)。

示例代码:

@SuppressWarnings("deprecation")
private LocationRequest createLocationRequest(long interval) {
    LocationRequest locationRequest;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        locationRequest = new LocationRequest.Builder(interval)
                .setPriority(Priority.PRIORITY_HIGH_ACCURACY)
                .setFastestInterval(interval / 2)
                .build();
    } else {
        locationRequest = LocationRequest.create();
        locationRequest.setInterval(interval);
        locationRequest.setFastestInterval(interval / 2);
        locationRequest.setPriority(Priority.PRIORITY_HIGH_ACCURACY);
    }
    return locationRequest;
}

2. 使用AndroidX Core库的兼容类

借助AndroidX提供的LocationRequestCompat类,它内部已封装版本兼容逻辑,无需手动写分支判断,也不会触发废弃方法的编译警告。

首先确保依赖AndroidX Core库(项目使用AndroidX时通常已包含):

implementation "androidx.core:core:1.10.1" // 或更高版本

然后直接调用兼容方法:

Java示例

import androidx.core.location.LocationRequestCompat;

private LocationRequest createLocationRequest(long interval) {
    return LocationRequestCompat.create(
            interval,
            interval / 2,
            Priority.PRIORITY_HIGH_ACCURACY,
            false
    );
}

Kotlin示例

import androidx.core.location.LocationRequestCompat

private fun createLocationRequest(interval: Long): LocationRequest {
    return LocationRequestCompat.create(
        interval = interval,
        fastestInterval = interval / 2,
        priority = Priority.PRIORITY_HIGH_ACCURACY,
        waitForAccurateLocation = false
    )
}

该方法会自动在API 31+环境下使用LocationRequest.Builder,低版本则调用原生create()方法,是更简洁的兼容方案。

内容的提问来源于stack exchange,提问作者Konstantin Konopko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:01:16