Android(安卓)定位当前位置可能出现的问题
android关于LocationManager的gps定位
LocationManager提供了两种定位当前位置的方法 GPS和NETWORK 其中gps的误差大概50m左右 network大概500m
起初当gps打开后 我使用Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);来获取location 可是一直为null不知道是什么原因 网上搜了很久终于找到了解决方案
android有一个Criteria类可以直接判断当前适合用gps或者network 并且设置LocationListener监听器实时更新location 直接上代码
private void getLocalAddress() {
LocationManager locationManager;
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
//updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
updateWithNewLocation(location);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "纬度:" + lat + "\n经度:" + lng;
} else {
latLongString = "无法获取地理信息";
}
Toast.makeText(SearchXiaoQuActivity.this, latLongString,
Toast.LENGTH_LONG).show();
}
更多相关文章
- android 项目中规范使用SharedPreferences
- Android(安卓)打开相机、相册获取图片文件,支持Android(安卓)9.0
- android 项目中规范使用SharedPreferences
- Android调用getSimSerialNumber获取iccid不完整
- android低功耗蓝牙APP开发问题记录
- [Android]googleMap的简单使用,地图定位,图标绘制。
- 获取Android设备的方向
- Android获取屏幕的宽和高
- 命令获取 Eclipse Android(安卓)证书指纹 MD5、SHA1