在android 23 以上 判断 定位服务 是否开启

在android中使用定位服务是很平常的事 一般大家都会使用
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//All location services are disabled
}
这种模式,但是在高版本的手机中locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)和locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
不管你是否开启 都会返回false

------------------------------解决方案如下------------

在API 23中,您需要添加“危险”权限检查以及检查系统本身

public static boolean isLocationServicesAvailable(Context context) {
int locationMode = 0;
String locationProviders;
boolean isAvailable = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF);
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
isAvailable = !TextUtils.isEmpty(locationProviders);
}
boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED);
boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
return isAvailable && (coarsePermissionCheck || finePermissionCheck);
}

你可能感兴趣的:(在android 23 以上 判断 定位服务 是否开启)