通过Android的原生api获取经纬度;

一些文章都是通过mLocationManager.getProviders,getLastKnownLocation来获取的,但是在一些手机上总是为空。

例如:在一些手机Android 5.0(api21 联想手机)上getLastKnownLocation获取总为空。

可以通过getBestProvider来获取provider然后通过getLastKnownLocation获取得到经纬度。

private Location getLastKnownLocation() {

//获取地理位置管理器

LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED

&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

// TODO:去请求权限后再获取

return null;

}

List providers = mLocationManager.getProviders(true);

Location bestLocation = null;

for (String provider : providers) {

Location l = mLocationManager.getLastKnownLocation(provider);

if (l == null) {

continue;

}

if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {

bestLocation = l;

}

}

// 在一些手机5.0(api21)获取为空后,采用下面去兼容获取。

if (bestLocation==null){

Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_COARSE);

criteria.setAltitudeRequired(false);

criteria.setBearingRequired(false);

criteria.setCostAllowed(true);

criteria.setPowerRequirement(Criteria.POWER_LOW);

String provider = mLocationManager.getBestProvider(criteria, true);

if (!TextUtils.isEmpty(provider)){

bestLocation = mLocationManager.getLastKnownLocation(provider);

}

}

return bestLocation;

}

// 使用

Location location = getLastKnownLocation();

LogUtils.d(TAG, "有位置权限-纬度:" + location.getLatitude() + " 经度:" + location.getLongitude());

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐