Kotlin: how to return running service instance in binder?

a 夏天 提交于 2021-02-16 16:10:57

问题


I have working Java code for Service and trying to convert it to Kotlin.

class MyService : Service() {

    companion object MyBinder : Binder() {
        fun getService() : MyService? {
            return MyService::class.objectInstance
        }
    }

    // service implementation

}

The problem is that in activities getService() always returns null. I am sure the service is started before, I see it in logcat. I suggest this auto generated line from Java code should be different but I cannot find the solution:

return MyService::class.objectInstance   

In Java code it is:

return MyService.this 

回答1:


Below code will help your

class MyService : Service() {

    inner class MyBinder : Binder() {
        fun getService() : MyService? {
            return this@MyService
        }
    }

    // service implementation

}

More info regarding this expression in Kotlin This Expression




回答2:


This is the short way doing it (including additionally onBind())

class MyService : Service() {

    override fun onBind(intent: Intent) = LocalBinder()

    inner class LocalBinder : Binder() {
        fun getService() = this@SensorService
    }
}


来源:https://stackoverflow.com/questions/46954444/kotlin-how-to-return-running-service-instance-in-binder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!