step2、扫描的回调
//蓝牙扫描回调接口
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback(){
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
if (device.getName() == null) {
return;
}
Log.e(“—>搜索到的蓝牙名字:”, device.getName());
//可以将扫描的设备弄成列表,点击设备连接,也可以根据每个设备不同标识,自动连接。
}
};
3、连接蓝牙
step1、获取设备的mac地址,然后连接。
//获取所需地址
String mDeviceAddress = device.getAddress();
BluetoothGatt mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
step2、onConnectionStateChange()被调用
- 连接状态改变时,mGattCallback中onConnectionStateChange()方法会被调用,当连接成功时,需要调用
mBluetoothGatt.discoverServices();
去获取服务。
step3、onServicesDiscovered()被调用
-
调用
mBluetoothGatt.discoverServices();
方法后,onServicesDiscovered()
这个方法会被调用,说明发现当前设备了。然后我们就可以在里面去获取BluetoothGattService和BluetoothGattCharacteristic。 -
下面就是mGattCallback回调方法。
// BLE回调操作
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,int newState){
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
// 连接成功
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
// 连接断开
Log.d(“TAG”,“onConnectionStateChange fail–>” + status);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
//发现设备,遍历服务,初始化特征
initBLE(gatt);
} else {