在Android平台上进行蓝牙开发,需要处理许多兼容性和稳定性问题。本文将介绍如何使用一个开源库BluetoothKit
来简化开发流程,并解决Android4.3及以后版本中蓝牙低功耗(BLE)的不稳定性问题。
项目GitHub地址:
要使用BluetoothKit
库,项目需要满足以下条件:
AndroidManifest.xml
中添加必要的权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
如果使用Gradle构建项目,只需在build.gradle
文件的dependencies部分添加以下行:
compile 'com.inuker.bluetooth:library:1.0.6'
首先,创建一个BluetoothClient
对象:
BluetoothClient mClient = new BluetoothClient(context);
该库支持蓝牙低功耗设备和经典设备的扫描,可以自定义扫描策略:
SearchRequest request = new SearchRequest.Builder()
.searchBluetoothLeDevice(3000, 3) // 扫描BLE设备3000毫秒,3次
.searchBluetoothClassicDevice(5000) // 然后扫描经典设备5000毫秒,1次
.searchBluetoothLeDevice(2000) // 最后扫描BLE设备2000毫秒
.build();
使用以下代码开始扫描:
mClient.search(request, new SearchResponse() {
@Override
public void onSearchStarted() {
}
@Override
public void onDeviceFounded(SearchResult device) {
}
@Override
public void onSearchStopped() {
}
@Override
public void onSearchCanceled() {
}
});
可以通过以下代码停止整个扫描:
mClient.stopSearch();
BleGattProfile
包含所有服务和特性的UUID。
mClient.connect(MAC, new BleConnectResponse() {
@Override
public void onResponse(int code, BleGattProfile profile) {
if (code == REQUEST_SUCCESS) {
}
}
});
注册连接状态监听器:
mClient.registerConnectStatusListener(MAC, mBleConnectStatusListener);
定义监听器:
private final BleConnectStatusListener mBleConnectStatusListener = new BleConnectStatusListener() {
@Override
public void onConnectStatusChanged(int status) {
if (status == STATUS_CONNECTED) {
} else if (status == STATUS_DISCONNECTED) {
}
}
};
取消注册监听器:
mClient.unregisterConnectStatusListener(MAC, mBleConnectStatusListener);
断开与设备的连接:
mClient.disconnect(MAC);
读取特性:
mClient.read(MAC, serviceUUID, characterUUID, new BleReadResponse() {
@Override
public void onResponse(int code, byte[] data) {
if (code == REQUEST_SUCCESS) {
}
}
});
写入特性,数据不应超过20字节:
mClient.write(MAC, serviceUUID, characterUUID, bytes, new BleWriteResponse() {
@Override
public void onResponse(int code) {
if (code == REQUEST_SUCCESS) {
}
}
});
无响应写入:
mClient.writeNoRsp(MAC, serviceUUID, characterUUID, bytes, new BleWriteResponse() {
@Override
public void onResponse(int code) {
if (code == REQUEST_SUCCESS) {
}
}
});
开启通知:
mClient.notify(MAC, serviceUUID, characterUUID, new BleNotifyResponse() {
@Override
public void onNotify(UUID service, UUID character, byte[] value) {
}
@Override
public void onResponse(int code) {
if (code == REQUEST_SUCCESS) {
}
}
});
关闭通知:
mClient.unnotify(MAC, serviceUUID, characterUUID, new BleUnnotifyResponse() {
@Override
public void onResponse(int code) {
if (code == REQUEST_SUCCESS) {
}
}
});
读取信号强度:
mClient.readRssi(MAC, new BleReadRssiResponse() {
@Override
public void onResponse(int code, Integer rssi) {
if (code == REQUEST_SUCCESS) {
}
}
});
mClient.refreshCache(MAC);