我是blueLEoth和Android的初学者。我需要创建一个将连接到设备的android应用程序(我具有mac地址和名称),并取决于距离将锁定/解锁设备。因此,我有4种状态:断开连接,远,锁定和解锁。应用程序应该没有任何按钮。开始后,就应该扫描并连接和更改手机上的图标。
我写了一些代码。此方法使用过滤器扫描设备。
public void ScanDevice() {
if (isScanning()) {
scanDisposable.dispose();
} else {
scanDisposable = rxBleClient.scanBleDevices(
new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
.build(),
new ScanFilter.Builder()
.setDeviceName("device_name")
.build()
)
.take(1)
.observeOn(AndroidSchedulers.mainThread())
.doFinally(this::dispose)
.subscribe(resultsAdapter::addScanResult, this::onScanFailure);
}
}
然后下一个方法是连接到该设备并观察其状态。
public void connectToDevice() {
ImageView imageView= (ImageView) findViewById(R.id.imageView6);
if (isConnected()) {
triggerDisconnect();
} else {
connectionDisposable = device.establishConnection(true)
.flatMapSingle(rxBleConnection -> rxBleConnection.readCharacteristic(CHARACTERISTIC))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
characteristicValue -> device.observeConnectionStateChanges()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
connectionState -> {
System.out.println("Connected");
if (connectionState.equals(RxBleConnection.RxBleConnectionState.CONNECTED)) {
Log.d(getClass().getSimpleName(), "Actual state " + connectionState.toString());
imageView.setImageResource(R.drawable.status_locked);
} else if (connectionState.equals(RxBleConnection.RxBleConnectionState.DISCONNECTED)) {
Log.d(getClass().getSimpleName(), "Actual state " + connectionState.toString());
imageView.setImageResource(R.drawable.status_disconnected);
}
},
throwable -> {
System.out.println("Disconnected");
// Handle an error here.
}
),
throwable -> {
// Handle an error here.
}
);
}
}
问题是我不知道设备何时更改状态以及如何更改图标。
我有快速执行此操作的代码,我很累将其重写为Java,但没有成功。
func enableBluetooth() {
connectedObservable = manager.observeState()
.startWith(manager.state)
.filter{ $0 == .poweredOn }
.timeout(3.0, scheduler: MainScheduler.instance)
.take(1)
.flatMap{ _ in self.manager.scanForPeripherals(withServices: nil) }
.filter{ $0.peripheral.name == DeviceService.proximityDeviceName.rawValue }
.take(1)
.flatMap{ return $0.peripheral.establishConnection() }
.do(onNext: { [unowned self] peripheral in
self.connectedDevice.value = peripheral
})
.flatMap{
return $0.discoverServices([DeviceService.proximityDevice.uuid])
}.asObservable()
.flatMap{ Observable.from($0) }
.flatMap{ $0.discoverCharacteristics([DeviceCharacteristic.proximityCharacteristic.uuid]) }.asObservable()
.flatMap{ Observable.from($0) }
.flatMap{ $0.observeValueUpdateAndSetNotification() }
.subscribe(onNext: { [unowned self] in
self.reading.value = ProximityDataModel(from: $0.value ?? Data())
})
}
我通过了所有有关rxandroidble的教程,但仍然无法解决。我不能继续前进。 我将非常感谢您的帮助!预先感谢。