Android BLE 蓝牙通信库,焦虑的移动互联网开发者如何破局

本文详细介绍了Android Bluetooth Low Energy(BLE)的使用,包括设备扫描、连接、读写Characteristic和Descriptor、开启关闭Notify等关键操作。通过BluetoothClient接口实现蓝牙通信,提供示例代码帮助开发者理解操作流程。
摘要由CSDN通过智能技术生成

所有接口都通过 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值