kotlin - 等待使用协程绑定(bind)服务

标签 kotlin

所以我有一个绑定(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/

相关文章:

android - 在 Android 上使用 gRPC 处理文件下载

spring - 如何在 Kotlin 和 Spring 中使用 setter 注入(inject)?

kotlin - 如何在 Kotlin 中向 StringBuilder 追加新行

kotlin - 如何使用 Gradle Kotlin buildSrc 插件自定义 KotlinCompile 任务?

android - 在 RecyclerView.Adapter 中绑定(bind) View 时出现 NullPointerException

android - 如何以编程方式将layout_width设置为ConstraintLayout的WRAP_CONTENT

performance - 如何获得一个函数在 Kotlin 中测试函数性能所需的时间

gradle - 如何修复 gradle/kotlin/netty 项目中 io.ktor.server.engine.CommandLineKt 抛出的 'Neither port nor sslPort specified'?

operators - 箭头 ("->") 运算符在 Kotlin 中的作用是什么?

android - 编译 Kotlin 序列化时出错