我想使用以下代码在我的 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 和网络)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!