开发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
相关产品推荐
相关产品推荐

