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 和网络)


- android 4中的android RadioButton问题 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01