Android BLE低功耗蓝牙开发
啦啦啦在上一個項目中有用到BLE低功耗藍牙開發,當時baidu google了很多資料,但大多數都是千篇一律,英文文檔我這種渣渣又看不懂。。。總之剛開始查的很痛苦。所以要把自己的踩坑之路寫下來記錄下,,,或許能幫到后來人呢?
概念
這是低功耗藍牙的官方文檔,英文好的同學可以直接看看這個:https://developer.android.google.cn/guide/topics/connectivity/bluetooth-le.html
低功耗藍牙是android4.3(API level18)之后才支持的.
一個低功耗藍牙終端包含多個Service,而Service中又包含多個Characteristic,一個Characteristic又包含一個Value和多個Descriptor.Characteristic是手機和BLE終端交換數據的關鍵.
這三部分都是通過UUID來獲取,UUID是他們的唯一標識.
鏈接
掃描的部分我們就不多說了,參考官方Demo寫的很詳細.主要說一說鏈接及發送消息等.
參考官方Demo,所有的鏈接等操作都是放在一個service中進行的,通過在service中發送廣播來通知activity來處理相關的數據.很簡單呦!我們先來看看service中都做了什么~
這是初始化藍牙適配器的方法,在開啟服務時調用.
/*** Initializes a reference to the local Bluetooth adapter.* 初始化一個藍牙適配器 里面會判斷系統版本,如果低于18則返回false(低于18不支持低功耗藍牙)** @return Return true if the initialization is successful.* 返回true表示初始化成功*/public boolean initialize() {// For API level 18 and above, get a reference to BluetoothAdapter through// BluetoothManager.if (mBluetoothManager == null) {mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);if (mBluetoothManager == null) {//無法初始化藍牙管理器Log.e(TAG, "Unable to initialize BluetoothManager.");return false;}}mBluetoothAdapter = mBluetoothManager.getAdapter();if (mBluetoothAdapter == null) {//無法獲取藍牙適配器Log.e(TAG, "Unable to obtain a BluetoothAdapter.");return false;}return true;}這是連接藍牙設備的方法,address就是藍牙設備的MAC地址,如果是掃描的則可以通過device.getAddress()來獲取到這個address.
/*** Connects to the GATT server hosted on the Bluetooth LE device.** 連接成功返回true 異步返回** @param address The device address of the destination device.** @return Return true if the connection is initiated successfully. The connection result* is reported asynchronously through the* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}* callback.*/public boolean connect(final String address) {if (mBluetoothAdapter == null || address == null) {//還沒有初始化或者指定地址Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");return false;}// Previously connected device. Try to reconnect. 以前連接的設備 嘗試重新連接if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)&& mBluetoothGatt != null) {Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");if (mBluetoothGatt.connect()) {mConnectionState = STATE_CONNECTING;return true;} else {return false;}}//根據mac地址獲取設備final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);//如果設備為null則表示未獲取到設備if (device == null) {Log.w(TAG, "Device not found. Unable to connect.");return false;}// We want to directly connect to the device, so we are setting the autoConnect//我們要直接連接到設備,所以我們設置自動連接// parameter to false.mBluetoothGatt = device.connectGatt(this, false, mGattCallback);//試圖創建一個新的連接Log.d(TAG, "Trying to create a new connection.");mBluetoothDeviceAddress = address;mConnectionState = STATE_CONNECTING;return true;}在調用connectGatt(context,autoConnect,callback)方法進行連接時,我們需要傳入一個context,一個boolean值,該參數表示以后是否需要自動連接到該設備,最后一個是藍牙連接的監聽回調對象BluetoothGattCallback,我們需要new 出來這個對象,重寫他的幾個方法,如下:
藍牙連接狀態改變的回調:在連接成功之后需要調用discoverServices方法來找服務,只有找到了服務才算是真正的連接成功.
@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {super.onConnectionStateChange(gatt, status, newState);if (newState == BluetoothProfile.STATE_CONNECTED) {mConnectionState = STATE_CONNECTING;//開始找服務,只有找到服務才算是真正的連接上了mBluetoothGatt.discoverServices();} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//發送廣播通知activity連接已斷開broadcastUpdate(ACTION_GATT_DISCONNECTED);mConnectionState = STATE_DISCONNECTED;} else {//發送廣播通知activity連接已斷開broadcastUpdate(ACTION_GATT_DISCONNECTED);mConnectionState = STATE_DISCONNECTED;}}發現服務的回調:
在找到服務之后就是真正的連接成功了,我在這里設置了對返回數據的監聽,后面具體說
Characteristic寫操作的結果回調:
這個監聽在分包發送的時候需要用到,在里面判斷的發送結果是否成功,成功的話則發送下一條數據,這樣可以保證分包發送的順序不會錯誤.
Characteristic狀態改變的回調:
這個方法挺重要的,藍牙廣播(是指藍牙設備本身發出的數據)出來的數據在這里獲取,發送指令后藍牙的回應也是在這里獲取.當然要走這個回調必須先設置相關的characteristic的監聽.
以上就是BluetoothGattCallback對象中要重寫的幾個方法,下面我們說一說characteristic的監聽設置
/*** 設置特征監聽*/public void enableTXNotification() {BluetoothGattService RxService = mBluetoothGatt.getService(SERVICE_UUID);if (RxService == null) {L.e("未找到藍牙中的對應服務");return;}BluetoothGattCharacteristic RxChar = RxService.getCharacteristic(RX_UUID);if (RxChar == null) {L.e("未找到藍牙中的對應特征");return;}//設置true為啟用通知,false反之mBluetoothGatt.setCharacteristicNotification(RxChar, true);//下面為開啟藍牙notify功能,向CCCD中寫入值1BluetoothGattDescriptor descriptor = RxChar.getDescriptor(CCCD);descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);mBluetoothGatt.writeDescriptor(descriptor);List<BluetoothGattDescriptor> descriptors = RxChar.getDescriptors();for (BluetoothGattDescriptor dp : descriptors) {dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);mBluetoothGatt.writeDescriptor(dp);}} 先通過Service的UUID找到對應的Service對象,再通過我們想要設置監聽的Characteristic的UUID找到相應的Characteristic對象,UUID都是藍牙設備廠商在文檔中提供的.找到相應的特征后調用setCharacteristicNotification方法開啟監聽,就可以在該特征狀態發生改變后走到onCharacteristicChanged方法中. 而藍牙的notify功能需要向CCCD中寫入值1才能開啟,CCCD值為:`public static final UUID CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");`往Characteristic中寫入數據:
我們知道低功耗藍牙的特點就是快速連接,超低功耗保持連接和傳輸數據,其缺點是傳輸速率很低,每次最多向Characteristic中寫入20字節的內容.因此當我們需要寫入的數據過大時就要使用分包發送.
先來看看如何往Characteristic中寫入數據吧
還是要先獲取到Characteristic對象,然后調用setValue方法設置我們需要寫入的數據,該方法接受byte[]和String,我們一般都是寫入byte[].基本都要求是十六進制byte[],很多同學會在這里糾結十六進制的轉換、數組中有些數據超出byte取值范圍了等問題,這些你其實完全不用考慮…不用非要寫成0x00這樣的形式,因為對于計算機來說都是一樣的,超出byte取值范圍也不用擔心,沒有什么影響的.不過如果可以的話最好還是能和你們的硬件工程師溝通一下.
分包發送的話還是需要與硬件工程師溝通具體的分包方法,寫入數據是延時多少毫秒,然后在上面onCharacteristicWrite方法中判斷寫入狀態,成功的話則寫入下一條數據,這樣來保證分包數據的順序不會錯亂.
總結
以上是生活随笔為你收集整理的Android BLE低功耗蓝牙开发的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于Springboot的新冠疫情可视化
- 下一篇: Android获取第三方音乐播放器的音乐