所有接口都通过 BluetoothClient 调用,涉及的常量如回调的错误码都在 Constants 类中。
设备扫描
支持经典蓝牙和 BLE 设备混合扫描,可自定义扫描策略。每次扫描都要创建新的 SearchRequest,不能复用。
SearchRequest request = new SearchRequest.Builder()
.searchBluetoothLeDevice(3000, 3) // 先扫 BLE 设备 3 次,每次 3s
.searchBluetoothClassicDevice(5000) // 再扫经典蓝牙 5s
.searchBluetoothLeDevice(2000) // 再扫 BLE 设备 2s
.build();
mClient.search(request, new SearchResponse() {
@Override
public void onSearchStarted() {
}
@Override
public void onDeviceFounded(SearchResult device) {
Beacon beacon = new Beacon(device.scanRecord);
BluetoothLog.v(String.format(“beacon for %s\n%s”, device.getAddress(), beacon.toString()));
}
@Override
public void onSearchStopped() {
}
@Override
public void onSearchCanceled() {
}
});
如果扫描不出来,可将 targetSdk 调到低于 6.0.
可以随时停止扫描:
mClient.stopSearch();
蓝牙开关
打开关闭蓝牙:
mClient.openBluetooth();
mClient.closeBluetooth();
判断蓝牙是否打开:
mClient.isBluetoothOpened();
蓝牙打开或关闭需要一段时间,可以注册回调监听状态,回调的参数如果是 true 表示蓝牙已打开,false 表示蓝牙关闭
mClient.registerBluetoothStateListener(mBluetoothStateListener);
private final BluetoothStateListener mBluetoothStateListener = new BluetoothStateListener() {
@Override
public void onBluetoothStateChanged(boolean openOrClosed) {
}
};
mClient.unr