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

开发GPS追踪App遇LocationRequest相关API过时,求解决办法

修复Android GPS追踪App中过时的LocationRequest方法

问题描述

首次用Java开发安卓GPS追踪App,代码中LocationRequest相关方法和常量均已过时,Android Studio给出了替代提示但无法正确修改,具体过时项包括:

  • new LocationRequest() 构造方法
  • setInterval()、setFastestInterval() 方法
  • setPriority() 方法及LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY、LocationRequest.PRIORITY_HIGH_ACCURACY 常量

修复方案

Google Play Services Location库的新版本采用Builder模式创建LocationRequest,并将优先级常量迁移至Priority类,同时更新了时间间隔相关方法名。以下是完整修复代码及说明:

修复后的代码

import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.Priority;

// 声明变量
LocationRequest locationRequest;

// 初始化LocationRequest
locationRequest = new LocationRequest.Builder(Priority.PRIORITY_BALANCED_POWER_ACCURACY)
        .setIntervalMillis(1000 * DEFAULT_UPDATE_INTERVAL)
        .setFastestIntervalMillis(1000 * FAST_UPDATE_INTERVAL)
        .build();

sw_gps.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (sw_gps.isChecked()) {
            // 切换为GPS高精度模式,重新构建LocationRequest
            locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY)
                    .setIntervalMillis(1000 * DEFAULT_UPDATE_INTERVAL)
                    .setFastestIntervalMillis(1000 * FAST_UPDATE_INTERVAL)
                    .build();
            tv_sensor.setText("Using GPS sensors");
        } else {
            // 切换为平衡功耗模式,重新构建LocationRequest
            locationRequest = new LocationRequest.Builder(Priority.PRIORITY_BALANCED_POWER_ACCURACY)
                    .setIntervalMillis(1000 * DEFAULT_UPDATE_INTERVAL)
                    .setFastestIntervalMillis(1000 * FAST_UPDATE_INTERVAL)
                    .build();
            tv_sensor.setText("Using Towers + WiFi");
        }

        // 重要:如果之前已通过FusedLocationProviderClient发起位置更新请求,需要重新调用requestLocationUpdates
        // 示例:
        // fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
    }
});

关键修改点说明

  • 创建方式变更:用LocationRequest.Builder替代直接new LocationRequest(),Builder是新版本推荐的不可变对象构建模式
  • 时间间隔方法更新:
    • 用setIntervalMillis(long)替代setInterval(long),参数仍为毫秒级间隔
    • 用setFastestIntervalMillis(long)替代setFastestInterval(long)
  • 优先级常量迁移:将LocationRequest.PRIORITY_*替换为Priority.PRIORITY_*,需确保导入com.google.android.gms.location.Priority类
  • 动态修改注意事项:新版本LocationRequest是不可变对象,无法直接修改已创建实例的属性,必须重新通过Builder构建新实例,之后需重新发起位置更新请求才能生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:15:35