-
第二个权限是允许程序发现和配对蓝牙设备。
-
因为只有在API18(Android4.3)以上的手机才支持ble开发,所以还要声明一个feature。
<uses-feature
android:name=“android.hardware.bluetooth_le”
android:required=“true” />
-
required为true时,应用只能在支持BLE的Android设备上安装运行
-
required为false时,Android设备均可正常安装运行,需要在代码运行时判断设备是否支持BLE。
-
**注意:**还得写上定位权限,要不然有的机型扫描不到ble设备。
step2、获取蓝牙适配器
BluetoothManager mBluetoothManager =(BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
- 如果mBluetoothAdapter为空,是因为手机蓝牙不支持与ble设备通讯,换句话说就是安卓手机系统在4.3以下了。
step3、判断手机蓝牙是否被打开
mBluetoothAdapter.isEnabled()
-
如果返回true,这个时候就可以扫描了
-
如果返回false,这时候需要打开手机蓝牙。 可以调用系统方法让用户打开蓝牙。
Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(enable);
2、搜索蓝牙
step1、开始扫描
//10s后停止搜索
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, 1000 * 10);
UUID[] serviceUuids = {UUID.fromString(service_uuid)};
mBluetoothAdapter.startLeScan(serviceUuids, mLeScanCallback);
-
startLeScan中,第一个参数是只扫描UUID是同一类的ble设备,第二个参数是扫描到设备后的回调。
-
因为蓝牙扫描比较耗电,建议设置扫描时间,一定时间后停止扫描。
-
如果不需要过滤扫描到的蓝牙设备,可用
mBluetoothAdapter.startLeScan(mLeScanCallback);
进行扫描。
<