Error getting Location Android (GPS and Network)(获取位置 Android 时出错(GPS 和网络))
问题描述
我想使用以下代码在我的 APP 中获取位置:
I want to get the location in my APP using the following code:
public Location getLocation() {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
try {
// Getting GPS and Network status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) return null;
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ((location != null && (location.getTime() + 60000 < System.currentTimeMillis())) ||
location == null){
location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return location;
}
当我使用 Nexus 4 时,它可以正常工作并且位置具有价值.但是当我在 Galaxy S2 location = null 中执行相同的代码时.
When I am using a Nexus 4 it works properly and location has a value. But when I am executing the same code in a Galaxy S2 location = null.
在调用该函数之前,我已经检查了 GPS 和网络是否都已启用.
Before calling the function I have checked that GPS and Network are both enabled.
你会如何修正这个函数?
How would you correcte this function?
在调用这个函数之前,我先调用这个函数:
Before calling this function I call this one:
public void startLocation() {
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} catch (Exception e) {
e.printStackTrace();
}
}
推荐答案
如果设备还没有找到位置,则返回null.
If the device have not yet found a location, it will return null.
我敢打赌,如果您打开 Google 地图并让它在打开您的应用程序之前找到您,它会按预期工作.
I bet if your open Google Maps and let it locate you before opening your app, it will work as expected.
查看我对定位服务GPS强制关闭的回答.这是一个关于如何实现回调以在位置可用时立即通知您的示例.
See my answer to Location servise GPS Force closed. This is an example on how you can implement a callback to let you know as soon as a location is available.
这篇关于获取位置 Android 时出错(GPS 和网络)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取位置 Android 时出错(GPS 和网络)


基础教程推荐
- 如何从 logcat 中删除旧数据? 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01