如何从RxAndroidBle获取BluetoothGatt对象

时间:2018-05-10 19:41:31

标签: android bluetooth-lowenergy rxandroidble

正如报道here,我有一个遗留应用程序拒绝连接到我试图支持的其中一个外围设备(与其他人一起工作正常)。 RxAndroidBle也成功连接,我想用它来建立连接并将其交给应用程序的其余部分。我需要从BluetoothGatt获取RxBleConnection对象;我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

在仔细研究了文档之后,我希望我已经做到了这一点。广泛的评论是为了我自己的利益,但也许他们会帮助其他人试图理解这一点。评论&更正欢迎。

public class GetGattOperation implements RxBleCustomOperation<BluetoothGatt> {

    private BluetoothGatt gatt;

    // How this may work:

    // You call rxBleConnection.queue( <instance of this class> )
    // It returns an Observable<T>--call it Observable A

    // The queue manager calls the .asObservable() method below,
    // which returns another Observable<T>--Observable B
    // It is placed in the queue for execution

    // When it's time to run this operation, ConnectionOperationQueue will
    // subscribe to Observable B (here, Observable.just( bluetoothGatt ))

    // Emissions from this Observable B (here, the bluetoothGatt) are forwarded to the Observable A returned by .queue()

    // Instances can be queued and received via a subscription to Observable A: 
    // rxBleConnection.queue( new GetGattOperation() ).subscribe( gatt -> {} );

    @Override
    public @NonNull Observable<BluetoothGatt> asObservable( BluetoothGatt bluetoothGatt,
                                                            RxBleGattCallback rxBleGattCallback,
                                                            Scheduler scheduler) throws Throwable {

        gatt = bluetoothGatt;
        return Observable.just( bluetoothGatt );  // return Observable B
    }


    public BluetoothGatt getGatt( ) {
        return gatt;
    }

}

主程序使用它(在.establishConnection()运算符链中):

.doOnNext( connection -> {
    rxBleConnection = connection;
    connection.queue( new GetGattOperation() )  // queue() returns Observable A
        .subscribe( gatt -> {  // receives events forwarded from Observable B
            Log.i( "Main", "BluetoothGatt received: " + gatt.toString() );
        } );
    } 
)