2016-07-22 25 views
0

当前正在修改sample code,并且在尝试建立连接并在一个活动中读取特征时遇到错误。如何建立连接,然后在一个活动中读取特征?

尝试从设备读取时,我得到BleAlreadyConnectedException。我首先连接onCreate。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_device); 

    // How to listen for connection state changes 
    bleDevice.observeConnectionStateChanges() 
      .compose(bindUntilEvent(DESTROY)) 
      .observeOn(AndroidSchedulers.mainThread()) 
      .subscribe(this::onConnectionStateChange); 

    if (isConnected()) { 
     triggerDisconnect(); 
    } else { 
     connectionSubscription = bleDevice.establishConnection(this, true) 
       .compose(bindUntilEvent(PAUSE)) 
       .observeOn(AndroidSchedulers.mainThread()) 
       .doOnUnsubscribe(this::clearSubscription) 
       .subscribe(this::onConnectionReceived, this::onConnectionFailure); 
    } 
} 

,然后试图读取onConnectionReceived特征...

private void onConnectionReceived(RxBleConnection connection) { 
    Log.d(TAG, "onConnectionReceived"); 
    connectionObservable = bleDevice 
      .establishConnection(this, false) 
      .takeUntil(disconnectTriggerSubject) 
      .compose(bindUntilEvent(PAUSE)) 
      .doOnUnsubscribe(this::clearSubscription) 
      .compose(new ConnectionSharingAdapter()); 

    if (isConnected()) { 
     connectionObservable 
       .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(uuid)) 
       .observeOn(AndroidSchedulers.mainThread()) 
       .subscribe(bytes -> { 
        Log.d(TAG, "onConnectionReceived:" + bytes); 
       }, this::onReadFailure); 
    } 
} 

你如何解决双.establishConnection(这一点,假)与ConnectionSharingAdapter?

回答

0

问题是你连接两次。您应该:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_device); 

    // How to listen for connection state changes 
    bleDevice.observeConnectionStateChanges() 
    .compose(bindUntilEvent(DESTROY)) 
    .observeOn(AndroidSchedulers.mainThread()) 
    .subscribe(this::onConnectionStateChange); 

    connectionObservable = bleDevice.establishConnection(this, true) 
    .compose(bindUntilEvent(PAUSE)) 
    .takeUntil(disconnectTriggerSubject) 
    .subscribeOn(Schedulers.io()) 
    .observeOn(AndroidSchedulers.mainThread()) 
    .doOnUnsubscribe(this::clearSubscription) 
    .compose(new ConnectionSharingAdapter()); 

    if (isConnected()) { 
     triggerDisconnect(); 
    } else { 
     connectionObservable.subscribe(this::onConnectionReceived, this::onConnectionFailure); 
    } 
} 

private void onConnectionReceived(RxBleConnection connection) { 
    Log.d(TAG, "onConnectionReceived"); 
    connection 
    .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(uuid)) 
    .subscribeOn(Schedulers.io()) 
    .observeOn(AndroidSchedulers.mainThread()) 
    .subscribe(bytes -> { 
     Log.d(TAG, "onValueReceived:" + bytes); 
    }, this::onReadFailure); 
} 

完整的示例是here

相关问题