最近总是有用户反馈说APP扫描不到设备,让我很费解了一段时间,尤其是华为和OPPO,公司还专门买了这款手机,然后测试没问题,直到一个偶然,我把手机定位给关了,才发现这个问题,Android 6.0 扫描设备需开启位置权限,用户突然一天把定位给关了,我们在扫描之前又没检测,唉,一个逻辑不严谨就会出现各种问题,现在记录一下
权限获取
<uses-permission android:name="android.permission.BLUETOOTH"/> 使用蓝牙所需要的权限
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 使用扫描和设置蓝牙的权限(申明这一个权限必须申明上面一个权限)
在Android5.0之前,是默认申请GPS硬件功能的。而在Android 5.0 之后,需要在manifest 中申明GPS硬件模块功能的使用。
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
在 Android 6.0 及以上,还需要打开位置权限。如果应用没有位置权限,蓝牙扫描功能不能使用(其它蓝牙操作例如连接蓝牙设备和写入数据不受影响)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
除了上面的设置之外,如果想设置设备只支持 BLE,可以加上下面这句话
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
同样,如果不想添加 BLE 的支持,那么可以设置 required="false"
然后可以在运行时判断设备是否支持 BLE,
// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
打开定位 (Location)
首先检查定位是否打开,可以像下面这样操作:
/**
* Location service if enable
*
* @param context
* @return location is enable if return true, otherwise disable.
*/
public static final boolean isLocationEnable(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean networkProvider = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean gpsProvider = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (networkProvider || gpsProvider) return true;
return false;
}
如果定位已经打开,可以搜索到 ble 设备;如果定位没有打开,则需要用户去打开,像下面这样:
private static final int REQUEST_CODE_LOCATION_SETTINGS = 2;
private void setLocationService() {
Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
this.startActivityForResult(locationIntent, REQUEST_CODE_LOCATION_SETTINGS);
}
进入定位设置界面,让用户自己选择是否打开定位。选择的结果获取:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_LOCATION_SETTINGS) {
if (isLocationEnable(this)) {
//定位已打开的处理
} else {
//定位依然没有打开的处理
}
} else super.onActivityResult(requestCode, resultCode, data);
}
网友评论