问题
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