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 和网络)
基础教程推荐
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01