所以我有一个绑定(bind)到服务的方法。
fun bindService() {
val intent = Intent(this, BluetoothService::class.java)
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
在 onCreate 方法中,我使用以下代码:
bindService()
launch {
delay(500L)
service = serviceConnection.serviceBinder?.getService() as BluetoothService
}
有没有比使用
delay()
更优雅的方法来等待服务绑定(bind)? ?
最佳答案
我刚刚写了这个,还没有尝试过,但希望它可以工作。魔法就在suspendCoroutine
,它会暂停当前的协程,然后为您提供一个后续的东西,您可以在以后使用它来恢复它。在我们的例子中,我们在调用 onServiceConnected 时恢复它。
// helper class which holds data
class BoundService(
private val context: Context,
val name: ComponentName?,
val service: IBinder?,
val conn: ServiceConnection) {
fun unbind() {
context.unbindService(conn)
}
}
// call within a coroutine to bind service, waiting for onServiceConnected
// before the coroutine resumes
suspend fun bindServiceAndWait(context: Context, intent: Intent, flags: Int) = suspendCoroutine<BoundService> { continuation ->
val conn = object: ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
continuation.resume(BoundService(context, name, service, this))
}
override fun onServiceDisconnected(name: ComponentName?) {
// ignore, not much we can do
}
}
context.bindService(intent, conn, flags)
}
// just an example
suspend fun exampleUsage() {
val bs = bindServiceAndWait(context, intent, Context.BIND_AUTO_CREATE)
try {
// ...do something with bs.service...
} finally {
bs.unbind()
}
}
关于kotlin - 等待使用协程绑定(bind)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381902/