Android 藍牙難點4.0總結
基礎請看藍牙官方文檔https://developer.android.google.cn/guide/topics/connectivity/bluetooth.html
//初始化ble設配器
private void initBle() {
BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = manager.getAdapter();
}
// 實現掃描回調接口
implements BluetoothAdapter.LeScanCallback
兩種方式本身實現或new 一個新class
掃描回調
bluetoothAdapter.startLeScan(this/leScanCallback)
// 掃描到新設備時,會回調該接口。
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {}
返回的有藍牙設備、無線接收信號強度(RSSI)、廣播包
byte[] scanRecord數據如下圖:
可根據 https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/ /藍牙官網協議文檔進行解析
如果知道要掃描的設備的serviceUUID 可以通過Android sdk 自身的方法進行掃描。
public boolean startLeScan(UUID[] serviceUuids, LeScanCallback callback) {
// 連接藍牙設備,device爲之前掃描得到的
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
使用BluetoothGattCallback 來跟設備進行通信
低功耗藍牙(BLE)設備的通信基本協議是 GATT, 要操作 BLE 設備,第一步就是要連接設備,其實就是連接 BLE 設備上的 GATT service。
// 實現連接回調接口[關鍵]
class BleGattCallback extends BluetoothGattCallback {
會繼承以下幾個關鍵方法
// 連接狀態改變(連接成功或失敗)時回調該接口
mBluetoothGatt是連接完成時的對象,調用這句後,會走回調函數的onServicesDiscovered方法。在這個方法中去獲取設備的一些服務,藍牙通道,然後通過這些通道去發送數據給外設。
在藍牙設備中, 其包含有多個BluetoothGattService, 而每個BluetoothGattService中又包含有多個BluetoothGattCharacteristic。
獲取到設備中的服務列表 mBluetoothGatt.getServices(); 或者通過uuid 來獲取某一個服務。
通過Gatt這個對像,就是藍牙連接完成後獲取到的對象,通過這個對象設置好指定的通道向設備中寫入和讀取數據。
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {}
// status 用於返回操作是否成功,會返回異常碼。
// newState 返回連接狀態,
public void onServicesDiscovered(BluetoothGatt gatt, int status) {}
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//數據在這裏接收
final byte[] data = characteristic.getValue();
根據藍牙協議進行數據解析
}
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {}
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {}
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {}
做通信要已知設備的通信協議,Service_UUID,Characteristic_UUID_WRITE,Characteristic_UUID_NOTIFY,如果多通道的話,要監聽所有通道,否則數據丟失,沒辦法對接收到的數據進行解析。
發送指令:監聽UUID_WRITE,
BluetoothGattCharacteristic write = gattService
.getCharacteristic(Characteristic_UUID_WRITE);
將byte[]寫入特徵
write.setValue(value);
通過gatt傳遞寫特徵gatt.writeCharacteristic(write);