Created
May 10, 2018 13:54
-
-
Save craigzour/edf7f3bd8bef4b162887b4244e27dc1f to your computer and use it in GitHub Desktop.
Here is a way of implementing pairing/bonding with RxAndroidBle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hello.world | |
import android.bluetooth.BluetoothDevice | |
import android.content.Context | |
import android.content.Intent | |
import android.content.IntentFilter | |
import android.content.BroadcastReceiver | |
import com.polidea.rxandroidble2.RxBleDevice | |
import io.reactivex.Completable | |
import io.reactivex.disposables.Disposables | |
/** | |
* Created by clement on 2017-08-24. | |
*/ | |
class PairingFailedException : RuntimeException() | |
internal object PairingManager { | |
/** | |
* @throws PairingFailedException | |
*/ | |
// TODO: try to understand why the popup is being displayed in the notification center (sometimes) ???!!! | |
fun pairWithDevice(context: Context, rxBleDevice: RxBleDevice): Completable { | |
return Completable.create { completion -> | |
when (rxBleDevice.bluetoothDevice.bondState) { | |
BluetoothDevice.BOND_BONDED -> completion.onComplete() | |
else -> { | |
val receiver = object : BroadcastReceiver() { | |
override fun onReceive(context: Context, intent: Intent) { | |
val deviceBeingPaired = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) | |
if (deviceBeingPaired.address == rxBleDevice.bluetoothDevice.address) { | |
val state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE) | |
when (state) { | |
BluetoothDevice.BOND_BONDED -> completion.onComplete() | |
BluetoothDevice.BOND_NONE -> completion.tryOnError(PairingFailedException()) | |
} | |
} | |
} | |
} | |
completion.setDisposable(Disposables.fromAction { context.unregisterReceiver(receiver) }) | |
context.registerReceiver(receiver, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) | |
val createBondResult = rxBleDevice.bluetoothDevice.createBond() | |
if (createBondResult == false) { | |
completion.tryOnError(PairingFailedException()) | |
} | |
} | |
} | |
} | |
} | |
} | |
And Then | |
return PairingManager | |
.pairWithDevice(this.context, rxBleDevice) | |
.andThen(connectToBleDevice) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@RobLewis
Java version (with lambda)