BleCentral is a wrapper library for easy establishing a BLE Central.
This library uses Kotlin coroutine so it is the better to use it in ViewModel
.
The first step is to include BleCentral in your project. Create a ./libs folder in your app module and copy blelib.aar to this folder. Then add this line to gradle file.
implementation fileTree(dir: 'libs', include: ['blelib.aar'])
var bleCentral: BleCentral = BleCentral(app, this)
class MainViewModel(app: Application) : AndroidViewModel(app), BleCentralCallback {
...
override fun onInitializeBleFailed(errorCode: Int) {
// Your code
}
override fun onScanFailed() {
// Your code
}
override fun onScanSuccess() {
// Your code
}
override fun onServicesDiscovered() {
// Your code
}
override fun onWriteRED() {
// Your code
}
override fun onWriteGREEN() {
// Your code
}
override fun onDisconnected() {
// Your code
}
You can start BLE Central normally, but it is better to use viewModelScope:
viewModelScope.launch {
withContext(Dispatchers.IO) {
bleCentral.start()
}
}
Stop Ble Central when it is no longer using. It is the best practice to stop BLE Central in onDestroy of activity.
bleCentral.stop()