Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android BLE 基礎框架使用詳解(ViseBluetooth)

編輯:關於 Android 程式設計

前言

研究了一段時間的藍牙開發後,我發現網上相關資料比較貧乏,不像其他 Android 資料那麼齊全,大部分內容都得從藍牙聯盟 SIG 官網(https://www.bluetooth.com/zh-cn/specifications)上查找,而且缺少一個穩定好用的基礎操作框架,開發中遇到的各種問題也十分頭疼。正是在這種情況下,該框架應運而生。它封裝了藍牙設備的基礎操作功能,調用簡單,並已在實際項目中驗證,還配有一個比較好用的 demo 演示。下文主要講述該框架的使用方式。

項目地址:https://github.com/xiaoyaoyou1212/BLE

項目引入:compile project('com.vise.xiaoyaoyou:baseble:1.0.0')

設備掃描

使用簡介

掃描包含三種方式。第一種是直接掃描所有設備,可設置循環掃描或超時時間,掃描到的設備可以添加到 BluetoothLeDeviceStore 中統一處理,使用方式如下:

 ViseBluetooth.getInstance(this).setScanTimeout(-1).startScan(new PeriodScanCallback() { @Override public void scanTimeout() { } @Override public void onDeviceFound(BluetoothLeDevice bluetoothLeDevice) { bluetoothLeDeviceStore.addDevice(bluetoothLeDevice); } });

第二種方式是掃描指定 Mac 地址的設備,一般需設置超時時間,掃描到指定設備後即停止掃描,使用方式如下:

 ViseBluetooth.getInstance(this).setScanTimeout(5000).startScan(new PeriodMacScanCallback() { @Override public void scanTimeout() { } @Override public void onDeviceFound(BluetoothLeDevice bluetoothLeDevice) { } });

第三種方式是掃描指定廣播名的設備,與第二種類似,也需設置超時時間,掃描到指定設備後也會停止掃描,使用方式如下:

 ViseBluetooth.getInstance(this).setScanTimeout(5000).startScan(new PeriodNameScanCallback() { @Override public void scanTimeout() { } @Override public void onDeviceFound(BluetoothLeDevice bluetoothLeDevice) { } });

其中掃描到的設備信息都統一放到 BluetoothLeDevice 中,裡面包含了設備的所有信息,下文會詳細講解具體包含哪些內容。

示例圖

設備連接

使用簡介

連接與掃描一樣也有三種方式。第一種是在掃描獲取到設備信息 BluetoothLeDevice 後才可使用,可設置連接超時時間,默認為 10 秒,使用方式如下:

 ViseBluetooth.getInstance(this).connect(bluetoothLeDevice, false, new IConnectCallback() { @Override public void onConnectSuccess(BluetoothGatt gatt, int status) { } @Override public void onConnectFailure(BleException exception) { } });

第二種方式是連接指定 Mac 地址的設備,使用前不需要掃描,它把掃描和連接放在一起,掃描到指定設備後自動連接,使用方式如下:

 ViseBluetooth.getInstance(this).connectByMac(mac, false, new IConnectCallback() { @Override public void onConnectSuccess(BluetoothGatt gatt, int status) { } @Override public void onConnectFailure(BleException exception) { } });

第三種方式是連接指定名稱的設備,與第二種類似,使用方式如下:

 ViseBluetooth.getInstance(this).connectByName(name, false, new IConnectCallback() { @Override public void onConnectSuccess(BluetoothGatt gatt, int status) { } @Override public void onConnectFailure(BleException exception) { } });

連接成功後就可以進行相關處理,回調已在底層做了線程切換,可以直接操作視圖。如果知道該設備服務的 UUID,可直接調用 ViseBluetooth.getInstance(this).withUUIDString(serviceUUID, characteristicUUID, descriptorUUID);,那麼在後續操作設備時就不需要再傳特征(BluetoothGattCharacteristic)和描述(BluetoothGattDescriptor)相關參數;如果連接成功後一直沒設置 UUID,那麼操作時就需要傳該參數,這一點在下文設備操作中會詳細講解,此處不再贅述。

示例圖

設備詳情

使用簡介

DEVICE INFO(設備信息)

獲取設備名稱(Device Name):bluetoothLeDevice.getName();

獲取設備地址(Device Address):bluetoothLeDevice.getAddress();

獲取設備類別(Device Class):bluetoothLeDevice.getBluetoothDeviceClassName();

獲取主要設備類別(Major Class):bluetoothLeDevice.getBluetoothDeviceMajorClassName();

獲取服務類別(Service Class):bluetoothLeDevice.getBluetoothDeviceKnownSupportedServices();

獲取配對狀態(Bonding State):bluetoothLeDevice.getBluetoothDeviceBondState();

RSSI INFO(信號信息)

獲取第一次信號時間戳(First Timestamp):bluetoothLeDevice.getFirstTimestamp();

獲取第一次信號強度(First RSSI):bluetoothLeDevice.getFirstRssi();

獲取最後一次信號時間戳(Last Timestamp):bluetoothLeDevice.getTimestamp();

獲取最後一次信號強度(Last RSSI):bluetoothLeDevice.getRssi();

獲取平均信號強度(Running Average RSSI):bluetoothLeDevice.getRunningAverageRssi();

SCAN RECORD INFO(廣播信息)

根據掃描到的廣播包,透過 AdRecordStore 獲取某個廣播數據單元 AdRecord 的類型編號 record.getType(),再根據編號獲取廣播數據單元的類型描述 record.getHumanReadableType() 以及該單元的長度與數據內容,最後透過 AdRecordUtil.getRecordDataAsString(record) 把數據內容轉換成具體字符串。

示例圖

設備操作

使用簡介

在操作設備前,首先要確保設備已連接成功。連接成功獲取到 BluetoothGatt 後,直接對服務的特征值 UUID 進行相關處理。特征值 UUID 有可讀、可寫、可通知、指示器四種,獲取過程如下:

 final String unknownServiceString = getResources().getString(R.string.unknown_service); final String unknownCharaString = getResources().getString(R.string.unknown_characteristic); final List> gattServiceData = new ArrayList<>(); final List>> gattCharacteristicData = new ArrayList<>(); mGattCharacteristics = new ArrayList<>(); // Loops through available GATT Services. for (final BluetoothGattService gattService : gattServices) { final Map currentServiceData = new HashMap<>(); uuid = gattService.getUuid().toString(); currentServiceData.put(LIST_NAME, GattAttributeResolver.getAttributeName(uuid, unknownServiceString)); currentServiceData.put(LIST_UUID, uuid); gattServiceData.add(currentServiceData); final List> gattCharacteristicGroupData = new ArrayList<>(); final List gattCharacteristics = gattService.getCharacteristics(); final List charas = new ArrayList<>(); // Loops through available Characteristics. for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { charas.add(gattCharacteristic); final Map currentCharaData = new HashMap<>(); uuid = gattCharacteristic.getUuid().toString(); currentCharaData.put(LIST_NAME, GattAttributeResolver.getAttributeName(uuid, unknownCharaString)); currentCharaData.put(LIST_UUID, uuid); gattCharacteristicGroupData.add(currentCharaData); } mGattCharacteristics.add(charas); gattCharacteristicData.add(gattCharacteristicGroupData); }

在獲取到 BluetoothGattCharacteristic 後,可進行如下操作:

- 設置通知服務

 ViseBluetooth.getInstance(this).enableCharacteristicNotification(characteristic, new IBleCallback() { @Override public void onSuccess(BluetoothGattCharacteristic bluetoothGattCharacteristic, int type) { } @Override public void onFailure(BleException exception) { } }, false);

其中最後一個參數用於設置該通知是否採用指示器方式,指示器方式為有應答的通知方式,在傳輸時更為可靠。如果在連接成功時已知該設備可通知的 UUID 並設置成功,那麼此處還可以這樣設置:

 ViseBluetooth.getInstance(this).enableCharacteristicNotification(new IBleCallback() { @Override public void onSuccess(BluetoothGattCharacteristic bluetoothGattCharacteristic, int type) { } @Override public void onFailure(BleException exception) { } }, false);

讀取信息

 ViseBluetooth.getInstance(this).readCharacteristic(characteristic, new IBleCallback() { @Override public void onSuccess(BluetoothGattCharacteristic bluetoothGattCharacteristic, int type) { } @Override public void onFailure(BleException exception) { } });

同樣,如果已設置過可讀的 UUID,那麼此處也可以通過如下方式讀取信息:

 ViseBluetooth.getInstance(this).readCharacteristic(new IBleCallback() { @Override public void onSuccess(BluetoothGattCharacteristic bluetoothGattCharacteristic, int type) { } @Override public void onFailure(BleException exception) { } });

寫入數據

 ViseBluetooth.getInstance(this).writeCharacteristic(characteristic, new byte[]{0x00,0x01,0x02}, new IBleCallback() { @Override public void onSuccess(BluetoothGattCharacteristic bluetoothGattCharacteristic, int type) { } @Override public void onFailure(BleException exception) { } });

同樣,如果在連接成功時設置過可寫 UUID,那麼此處也可以通過如下方式寫入數據:

 ViseBluetooth.getInstance(this).writeCharacteristic(new byte[]{0x00,0x01,0x02}, new IBleCallback() { @Override public void onSuccess(BluetoothGattCharacteristic bluetoothGattCharacteristic, int type) { } @Override public void onFailure(BleException exception) { } });

此處的數據 new byte[]{0x00,0x01,0x02} 為模擬數據,使用時替換為真實數據即可。切記每次發送的數據必須在 20 個字節以內,如果大於 20 字節,可採用分包機制進行處理。

示例圖

總結

從以上描述可以知道,設備相關的所有操作都統一交給 ViseBluetooth 處理,而且該類採用單例模式,全局只有一個,管理很方便。連接設備成功時會自動獲得一個 BluetoothGatt,斷開連接時會把該 BluetoothGatt 關閉,上層不用關心連接數最大為 6 的限制問題,只需在需要釋放資源時調用 ViseBluetooth.getInstance(this).clear(); 即可,簡單易用,這也正是該項目的宗旨。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved