Cil*_*nco 7 android bluetooth bluetooth-lowenergy
我有一个蓝牙耳机,它与我的Nexus 5X(运行Android 7.1)配对,我想连接到耳机的GATT服务器.我用以下代码尝试了它:
private BluetoothGattCallback btleGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.d(TAG, "onConnectionStateChange: " + status + ", " + newState);
if(newState == STATE_CONNECTED) {
Log.d(TAG, "Device connected");
boolean ans = gatt.discoverServices();
Log.d(TAG, "Discover Services started: " + ans);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.d(TAG, "Number of Services: " + gatt.getServices().size());
}
};
public void onDeviceClicked(BluetoothDevice device) {
BluetoothGatt gatt = device.connectGatt(this, false, btleGattCallback);
Log.d(TAG, "Connected to GATT: " + gatt.connect());
}
Run Code Online (Sandbox Code Playgroud)
如果我在我的UI中单击耳机,onDeviceClicked则会调用此日志输出:
<!-- language: lang-none -->
Connected to GATT: true
onConnectionStateChange: 0, 2 // GATT_SUCCESS, STATE_CONNECTED
Device connected
Discover Services started: true
Run Code Online (Sandbox Code Playgroud)
你可以看到onServicesDiscovered永远不会被解雇.我试着打电话connectGatt给TRANSPORT_LE(参考),但后来我得到了onConnectionStateChange: 133, 0.我也发现了这个问题,这就是我gatt.connect()在答案二中提到的方法.
你有什么想法我没有得到onServicesDiscovered回调吗?
ayv*_*azj 10
Android上的BLE可能有点挑剔.
确保在UI线程上调用mBluetoothGatt.discoverServices().
if(newState == STATE_CONNECTED) {
Log.d(TAG, "Device connected");
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
boolean ans = mBluetoothGatt.discoverServices();
Log.d(TAG, "Discover Services started: " + ans);
}
});
}
Run Code Online (Sandbox Code Playgroud)
还可以尝试创建BluetoothGatt gatt字段变量而不是局部变量.
如果您正在进行任何重要工作,请尝试使用掩盖所有特性的库,以便您可以专注于高级逻辑. https://github.com/Polidea/RxAndroidBle.
这是一个如何阅读特征的例子.
connectionObservable
.flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUuid))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bytes -> {
readOutputView.setText(new String(bytes));
readHexOutputView.setText(HexString.bytesToHex(bytes));
writeInput.setText(HexString.bytesToHex(bytes));
}, this::onReadFailure);
Run Code Online (Sandbox Code Playgroud)
或者使用Java 7语法
connectionObservable
.flatMap(new Func1<RxBleConnection, Observable<byte[]>>() {
@Override
public Observable<byte[]> call(RxBleConnection rxBleConnection) {
return rxBleConnection.readCharacteristic(characteristicUuid);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<byte[]>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
onReadFailure(e);
}
@Override
public void onNext(byte[] bytes) {
readOutputView.setText(new String(bytes));
readHexOutputView.setText(HexString.bytesToHex(bytes));
writeInput.setText(HexString.bytesToHex(bytes));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5237 次 |
| 最近记录: |