Android LocationManager.getLastKnownLocation() 返回 null [英] Android LocationManager.getLastKnownLocation() returns null

查看:16
本文介绍了Android LocationManager.getLastKnownLocation() 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在应用程序中只对 gps 坐标进行一次采样.我不想创建一个 LocationListener 对象来不断获取 gps 更新.我想等到收到坐标后,再继续执行其他任务.

So I'm trying to sample the gps coordinates just once in an application. I don't want to create a LocationListener object to constantly get gps updates. I want to wait until receiving the coordinates, and then proceed on to another task.

这是一个代码片段

LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, true);
Location loc = lm.getLastKnownLocation(provider);

loc 变量在模拟器中始终为空.我尝试使用命令geo fix latitude longitude"来设置它,我也尝试使用 DDMS 方式来设置它.这两种方法都对代码没有任何影响.该代码段也不会导致任何异常.

The loc variable is always null in the emulator. I tried using the command "geo fix latitude longitude" to set it, and also I tried using the DDMS way of setting it. Neither method had any effect on the code. Also the snippet isn't causing any exceptions.

感谢您的帮助.

推荐答案

请求更新位置的调用没有阻塞,因此它不会在那里等待.此外,模拟器中的提供程序可能尚未启动.

The call to request update for a location is not blocking, hence it wont wait there. Also the provider in emulator may not have been started.

可能的检查可能是查看其中的设置是否禁用 gps 提供程序?然后发送地理修复.

A possible check could be to see if the settings in it disable gps provider ? then send geo fix.

但是,我会使用位置侦听器,这在您的情况下是理想的,因为您需要地理修复才能继续进行.位置侦听器用于在位置更改时接收来自 LocationManager 的通知.您可以在第一次 geofix 后取消注册监听器.

However, I would use Location Listener, it would be ideal in your case since you need a geo fix to proceed further.Location Listener is Used for receiving notifications from the LocationManager when the location has changed. You can unregister the listener after first geofix.

注意:在设备上获取当前位置可能需要一些时间,即使在设备上也可能返回 null.

Note: It can take some time on device to get current location, and even on device this can return null.

这篇关于Android LocationManager.getLastKnownLocation() 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆