所以我有一个绑定到服务的方法。
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()?
小智 5
我刚刚写了这个,还没有尝试过,但希望类似的东西可以工作。神奇之处在于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()
    }
}
| 归档时间: | 
 | 
| 查看次数: | 1696 次 | 
| 最近记录: |