getLastKnownLocation()返回null的解决

本文探讨了解决Android应用中使用LocationManager.getLastKnownLocation获取GPS位置时出现空指针异常的问题。通过设置权限、手动配置经纬度及采用LocationListener监听位置更新等方法,有效地解决了定位失败的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用LocationManager.getLastKnownLocation("gps")获取gps定位的过程中老是报空指针异常 

在网上百度查了不少资料发现这个问题多出现在2.0以上版本 
解决方法多是: 
1.在AndroidManifest.xml中添加 

 

 

 

2.在emulator control中手动设置经纬度 

但是我的程序这些都写了依旧报空指针 

后来在外国论坛上终于找到一些启发 
一个哥们这样写代码

 

 

 

我试了一下还真有效,他的解释是用debug发现getLastKnownLocation()方法不是一次就能定位的,必须多次才能成功。 

但是显然这样用循环一直等待很没效率,所以我重写了MapActivity的方法

 

 

 

一样也成功了。。 

在外国技术论坛上找了个解释,个人感觉很贴切: 

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. 

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

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. 

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


具体可见 http://stackoverflow.com/questions/1608632/android-locationmanager-getlastknownlocation-returns-null

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值