【问题标题】:Location return null on the phone手机上的位置返回 null
【发布时间】:2020-12-10 15:53:04
【问题描述】:

我想检查我当前的纬度和经度。这段代码在模拟器上工作,但是当我在手机上检查时我有空。(android 10)
手机上的应用有定位权限。

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if(location!=null){
                MyLong=location.getLongitude();
                MyLat=location.getLatitude();
                test.setText(MyLat+" " +MyLong);
            }
            else{
                test.setText("null");
            }
        }
    });

【问题讨论】:

  • 您是否添加了必要的权限?

标签: android location


【解决方案1】:

基于official android documentation,在某些情况下,最后一个已知位置可能为空,而这些情况是

  • 位置在设备设置中被关闭。结果可能是 null 即使之前检索到最后一个位置,因为 禁用位置也会清除缓存。
  • 设备从未记录其位置,这可能是 新设备或已恢复出厂设置的设备。
  • 设备上的 Google Play 服务已重启,但没有 已请求位置的活动 Fused Location Provider 客户端 服务重启后

在这些情况下,您应该request location updates。你可以查看example of Google's Codelabs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2020-03-24
    • 2011-11-03
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多