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 
                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
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
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With