我想使用 Android 应用程序获取我的 GPS 坐标。我开始开发,可以得到GPS坐标,但是不准确。我想使用 NETWORK_PROVIDER,但此提供商的 Location 始终为空。更有趣的是,isProvicerEnabled 返回 true。
我使用了这个线程中的示例(最佳答案) enter link description here
private void _getLocation() {
// Get the location manager
try {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Location location = null;
double latitude = -1;
double longitude = -1;
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
if (isNetworkEnabled) {
showToast("network");
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
1000,
0, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
else if (isGPSEnabled) {
showToast("gps");
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
1000,
0, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
showToast("" + latitude + longitude);
} catch (Exception e) {
e.printStackTrace();
}
我拥有 list 中的所有权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
我知道代码有问题,但目前仅用于测试。我想念什么吗?我在很多地方找到了类似的例子,看起来很直白,所以我有点困惑。 我的手机工作正常,GPS 和网络工作正常。例如,我的谷歌地图应用程序运行良好。有什么建议吗?
最佳答案
请不要使用此代码。这不好。它有很多错误。此外,如果还没有位置,getLastKnownLocation 将返回 null。如果电话中没有人使用 requestUpdates,它总是会这样做。
您的代码取自一个发布在一个名为 GPSTracker 的非常古老的线程上的类。几个月来我一直试图取消该代码——它造成的问题远多于它的帮助。如果您想要更好的示例代码,请尝试 http://gabesechansoftware.com/location-tracking/这是我写的一篇关于该代码有多糟糕的博客文章。它将向您展示正确的方法,并解释该代码的一些错误。
关于Android LocationManager 网络提供者返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24972728/