項(xiàng)目需要接入兩個(gè)低功耗藍(lán)牙設(shè)備(BLE),并且與之交互(讀/寫)數(shù)據(jù),所以看了下官方對(duì)于這塊兒的介紹,總結(jié)了一下BLE開發(fā)中一些需要注意的地方以及基本流程。
BLE開發(fā)需要Android 4.3 (API level 18) 及以上
一.添加權(quán)限
為了能正常使用藍(lán)牙相關(guān)功能(掃描等),首先需要添加以下權(quán)限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
在Android6.0及以上系統(tǒng)中,我們需要?jiǎng)討B(tài)申請(qǐng)權(quán)限,這里推薦使用RxPermissions
簡(jiǎn)單介紹下RxPermissions如何引入。
1.在根build文件中添加代碼:
...
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
...
2.在對(duì)應(yīng)moudle的build文件中添加依賴:
...
dependencies {
implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
}
...
3.使用:
RxPermissions rxPermissions=new RxPermissions(this);
rxPermissions.request(Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe(granted -> {
if (granted) {
//權(quán)限允許成功
}
});
如果想了解RxPermissions更多用法,戳這里。
二.判斷設(shè)備是否支持藍(lán)牙
這里有兩種處理方式:
- 如果你想讓只有支持BLE的手機(jī)才能安裝你的應(yīng)用程序的話,可以在清單文件中添加如下內(nèi)容,這樣的話如果設(shè)備不支持BLE的話你的應(yīng)用都裝不上,當(dāng)然這種方式不太友好:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
- 在代碼中判斷當(dāng)前設(shè)備是否支持BLE,以對(duì)用戶做出反饋。
首先,在清單文件中聲明需要使用BLE特性,不過(guò)required這里設(shè)置為false,然后在app運(yùn)行時(shí)通過(guò)PackageManager.hasSystemFeature()來(lái)判斷設(shè)備是否支持ble:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
三.掃描藍(lán)牙設(shè)備
BLE設(shè)備的掃描由BluetoothManager對(duì)象提供方法來(lái)實(shí)現(xiàn),有兩個(gè)掃描方法:
public boolean startLeScan(BluetoothAdapter.LeScanCallback callback) {
throw new RuntimeException("Stub!");
}
public boolean startLeScan(UUID[] serviceUuids, BluetoothAdapter.LeScanCallback callback) {
throw new RuntimeException("Stub!");
}
第二個(gè)方法允許我們提供特定的UUID,來(lái)掃描特定的設(shè)備,掃描結(jié)果通過(guò)BluetoothAdapter.LeScanCallback接口回調(diào)給我們:
public interface LeScanCallback {
/**
* Callback reporting an LE device found during a device scan initiated
* by the {@link BluetoothAdapter#startLeScan} function.
*
* @param device Identifies the remote device
* @param rssi The RSSI value for the remote device as reported by the
* Bluetooth hardware. 0 if no RSSI value is available.
* @param scanRecord The content of the advertisement record offered by
* the remote device.
*/
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord);
}
四.獲取遠(yuǎn)程BLE設(shè)備
在掃描出設(shè)備以后,我們一般會(huì)選擇某個(gè)掃描出來(lái)的設(shè)備,通過(guò)其地址獲取一個(gè)遠(yuǎn)程的藍(lán)牙設(shè)備對(duì)象。
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address)
五.連接BLE設(shè)備的GATT服務(wù)
與BLE設(shè)備交互的第一步是連接到它,更具體地說(shuō),連接到設(shè)備上的GATT服務(wù)。要在BLE設(shè)備上連接到GATT服務(wù),可以使用connectGatt()方法。該方法接受三個(gè)參數(shù):一個(gè)上下文對(duì)象、autoConnect(布爾值表示是否在BLE設(shè)備可用時(shí)自動(dòng)連接到該設(shè)備),以及對(duì)BluetoothGattCallback的引用:
mBluetoothGatt = device.connectGatt(context, true, mGattCallback);
以上代碼可以連接到由BLE設(shè)備托管的GATT服務(wù),并返回一個(gè)BluetoothGatt實(shí)例,然后可以使用它來(lái)執(zhí)行GATT客戶端操作,例如寫數(shù)據(jù)等。呼叫者(Android應(yīng)用程序)是GATT客戶端。連接狀態(tài),以及GATT的數(shù)據(jù)變化等通過(guò)BluetoothGattCallback接口回調(diào)給客戶端(APP)。
一般使用BluetoothGattCallback的這些回調(diào)方法:
1.獲取連接狀態(tài),在連接成功時(shí)掃描設(shè)備服務(wù)
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
if (connectChangedListener != null) {
connectChangedListener.onConnected();
}
mConnectionState = STATE_CONNECTED;
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
if (connectChangedListener != null) {
connectChangedListener.onDisconnected();
}
mConnectionState = STATE_DISCONNECTED;
}
}
2.獲取服務(wù),特性等
一個(gè)BLE設(shè)備可能有多個(gè)服務(wù)BluetoothGattService,同樣每個(gè)服務(wù)可以有多個(gè)BluetoothGattCharacteristic特性。
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = mBluetoothGatt.getServices();
for (int i = 0; i < services.size(); i++) {
HashMap<String, BluetoothGattCharacteristic> charMap = new HashMap<>();
BluetoothGattService bluetoothGattService = services.get(i);
String serviceUuid = bluetoothGattService.getUuid().toString();
List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
for (int j = 0; j < characteristics.size(); j++) {
charMap.put(characteristics.get(j).getUuid().toString(), characteristics.get(j));
}
servicesMap.put(serviceUuid, charMap);
}
BluetoothGattCharacteristic bluetoothGattCharacteristic = getBluetoothGattCharacteristic(UUID_SERVICE, UUID_CHARACTERISTIC);
if (bluetoothGattCharacteristic == null)
return;
enableGattServicesNotification(bluetoothGattCharacteristic);
} else {
Log.w(TAG, " --------- onServicesDiscovered received: " + status);
}
}
在上面的代碼中,我們將BLE設(shè)備的所有BluetoothGattService和BluetoothGattCharacteristic全部保存下來(lái),但是在實(shí)際需求中,我們一般只會(huì)與某個(gè)特定BluetoothGattService中的某個(gè)特性BluetoothGattCharacteristic進(jìn)行數(shù)據(jù)讀寫。判斷條件就是這里的UUID_SERVICE和UUID_CHARACTERISTIC,這兩個(gè)UUID一般提供BLE設(shè)備的時(shí)候會(huì)一并提供給我們。
找到這個(gè)特定的BluetoothGattCharacteristic后,我們希望它發(fā)生改變時(shí)可以得到通知,可以使用setCharacteristicNotification()方法為特性設(shè)置通知:
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(UUID_DESCRIPTOR));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
3.監(jiān)聽數(shù)據(jù)變化
經(jīng)過(guò)以上設(shè)置,我們就可以在onCharacteristicChanged回調(diào)方法中獲取BLE設(shè)備發(fā)過(guò)來(lái)的數(shù)據(jù)了:
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
//解析數(shù)據(jù)
parseData(characteristic);
}
當(dāng)然,我們也可以用第五步中獲取的mBluetoothGatt來(lái)向BLE設(shè)備發(fā)送數(shù)據(jù):
mBleGattCharacteristic.setValue(HexUtil.hexStringToBytes(value));
boolean b=mBluetoothGatt.writeCharacteristic(mBleGattCharacteristic);
以上,就是Android端與BLE設(shè)備通信的基本開發(fā)流程,這里我抽成了一個(gè)Demo,項(xiàng)目目錄如下:

幾點(diǎn)說(shuō)明:
- 因?yàn)槲疫@里需求是接入兩個(gè)BLE設(shè)備,所以我抽取了一個(gè)BluetoothLeDeviceBase,代表基類設(shè)備,將一些通用的屬性和操作封裝在了這里
- BluetoothLeDeviceA,BluetoothLeDeviceB代表具體的某個(gè)BLE設(shè)備,每個(gè)設(shè)備可能有不同之處,例如數(shù)據(jù)解析方式等。
完整代碼地址:https://github.com/SolveBugs/BlogPracticeDems,目前只是基本的封裝,后續(xù)會(huì)繼續(xù)完善。
選擇bluetoothbledemo這個(gè)moudle運(yùn)行即可,界面如下:
