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

Android模拟器中onLocationChanged仅触发一次,如何持续监听GPS位置变化?

问题原因&解决方案

嘿,你已经找对了接收位置更新的核心方法——onLocationChanged,但你的代码里藏了一个“自断后路”的操作,导致它只触发一次!

问题根源

看你onLocationChanged方法的最后几行:

if(client != null) { 
    LocationServices.FusedLocationApi.removeLocationUpdates(client, this); 
}

这行代码的作用是立刻终止位置更新请求,相当于你刚收到一次位置数据,就主动告诉系统“别再给我发了”,自然只会触发一次回调。

修复步骤

  1. 移除停止更新的代码,让系统持续推送位置变化:
    修改后的onLocationChanged方法:
@Override 
public void onLocationChanged(Location location) { 
    lastLocation = location; 
    if (currentLocationMarker != null) { 
        currentLocationMarker.remove(); 
    } 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
    getLatitude = location.getLatitude(); 
    getLongitude = location.getLongitude(); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    mMap.animateCamera(CameraUpdateFactory.zoomBy(10)); 
    // 删掉下面这段停止更新的代码!
    // if(client != null) { 
    //     LocationServices.FusedLocationApi.removeLocationUpdates(client, this); 
    // } 
} 
  1. 在合适时机主动停止更新(避免资源浪费)
    虽然要持续捕获位置,但在页面暂停或销毁时,记得主动停止更新,防止内存泄漏和不必要的电量消耗:
@Override
protected void onPause() {
    super.onPause();
    if (client != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (client != null && client.isConnected()) {
        client.disconnect();
    }
}

模拟器测试小技巧

在Android模拟器里,你可以这样模拟位置变化来测试回调:

  • 点击模拟器右侧的扩展控制按钮(三个点的图标)
  • 切换到Location标签页
  • 输入新的经纬度后点击SEND,或者选择预设位置,就能触发onLocationChanged回调了

额外优化提示

你onConnected里的位置请求配置是合理的:

locationRequest.setInterval(1000); // 每秒请求一次位置
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

如果不需要这么高频的更新,可以把setInterval的值调大(比如改成5000就是5秒一次),平衡精度和资源消耗。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:55:13