通过 BLE 扫描和广播提供的开放能力,可以根据指定状态获取外围设备、启动或停止 BLE 扫描、广播。
接口名 | 功能描述 |
---|---|
startScan(List<BleScanFilter> filters) | 进行 BLE 蓝牙扫描,并使用 filters 对结果进行过滤。 |
stopScan() | 停止 BLE 蓝牙扫描。 |
getDevicesByStates(int[] states) | 根据状态获取连接的外围设备。 |
BleCentralManager(BleCentralManagerCallback callback) | 获取中心设备管理对象。 |
接口名 | 功能描述 |
---|---|
onScanCallback(BleScanResult result) | 扫描到 BLE 设备的结果回调。 |
onStartScanFailed(int resultCode) | 启动扫描失败的回调。 |
接口名 | 功能描述 |
---|---|
BleAdvertiser(Context context, BleAdvertiseCallback callback) | 用于获取广播操作对象。 |
startAdvertising(BleAdvertiseSettings settings, BleAdvertiseData advData, BleAdvertiseData scanResponse) | 进行 BLE 广播,第一个参数为广播参数,第二个为广播数据,第三个参数是扫描和广播数据参数的响应。 |
stopAdvertising() | 停止 BLE 广播。 |
startResultEvent(int result) | 广播回调结果。 |
// 实现扫描回调
public class ScanCallback implements BleCentralManagerCallback{
List<BleScanResult>results = new ArrayList<BleScanResult>();
@Override
public void onScanCallback(BleScanResult var1) {
// 对扫描结果进行处理
results.add(var1);
}
@Override
public void onStartScanFailed(int var1) {
HiLog.info(TAG,"Start Scan failed,Code:" + var1);
}
}
// 获取中心设备管理对象
private ScanCallback centralManagerCallback = new ScanCallback();
private BleCentralManager centralManager = new BleCentralManager(centralManagerCallback);
// 创建扫描过滤器然后开始扫描
List<BleScanFilter> filters = new ArrayList<BleScanFilter>();
centralManager.startScan(filters);
// 实现 BLE 广播回调
private BleAdvertiseCallback advertiseCallback = new BleAdvertiseCallback() {
@Override
public void startResultEvent(int result) {
if(result == BleAdvertiseCallback.RESULT_SUCC){
// 开始 BLE 广播成功
}
else {
// 开始 BLE 广播失败
}
}
};
// 获取 BLE 广播对象
private BleAdvertiser advertiser = new BleAdvertiser(this,advertiseCallback);
// 创建 BLE 广播参数和数据
private BleAdvertiseData data = new BleAdvertiseData.Builder()
.addServiceUuid(SequenceUuid.uuidFromString(Server_UUID)) // 添加服务的 UUID
.addServiceData(SequenceUuid.uuidFromString(Server_UUID),new byte[]{0x11}) // 添加广播数据内容
.build();
private BleAdvertiseSettings advertiseSettings = new BleAdvertiseSettings.Builder()
.setConnectable(true) // 设置是否可连接广播
.setInterval(BleAdvertiseSettings.INTERVAL_SLOT_DEFAULT) // 设置广播间隔
.setTxPower(BleAdvertiseSettings.TX_POWER_DEFAULT) // 设置广播功率
.build();
// 开始广播
advertiser.startAdvertising(advertiseSettings,data,null);
(c) 2024 chaojicainiao.com MIT license