我想使用Android App获得我的GPS坐标。我开始开发,我可以获得GPS坐标,但它们不准确。我想使用NETWORK_PROVIDER,但是这个提供程序的位置总是空的。更有趣的是,isProvicerEnabled返回true。
我从这个线程使用的例子(最佳答案)在这里输入链接描述
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();
}
我拥有清单
中的所有权限<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/,这是我写的一篇关于代码有多糟糕的博客文章。它将向您展示正确的方法,并解释代码中的一些错误。