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 {
Log.d(“TAG”,“onServicesDiscovered fail–>” + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status){
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
// 收到的数据
byte[] receiveByte = chara