经常要用到,所以记录下来
/**
* 请求权限的Code
*/
public static final int REQUEST_PERMISSION_CODE = 1500;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PERMISSION_CODE) {
checkPermission();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_CODE) {
checkPermission();
}
}
/**
* 检查权限
*/
private void checkPermission() {
// 没有打开蓝牙就请求打开蓝牙
if (!hasBluetooth()) {
requestBluetooth();
return;
}
// 没有定位权限就请求定位权限
if (!hasLocationPermission()) {
requestLocationPermission(this);
return;
}
// 没有定位服务就请求定位服务
if (!hasLocationService()) {
requestLocationService();
return;
}
// 权限都有了,OK
// TODO
}
/**
* 是否有定位权限
*
* @return boolean
*/
private boolean hasLocationPermission() {
return ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
/**
* 蓝牙是否打开
*
* @return boolean
*/
private boolean hasBluetooth() {
return BluetoothAdapter.getDefaultAdapter().isEnabled();
}
/**
* 定位服务是否打开
*
* @return boolean
*/
private boolean hasLocationService() {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (locationManager == null) {
return false;
}
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
/**
* 申请定位权限
*/
private void requestLocationPermission(Activity activity) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_CODE);
}
/**
* 申请打开蓝牙
*/
private void requestBluetooth() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_PERMISSION_CODE);
}
/**
* 申请打开定位服务
*/
private void requestLocationService() {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_PERMISSION_CODE);
}