Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: how to return running service instance in binder?

Tags:

android

kotlin

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 
like image 207
Almaz Avatar asked Oct 26 '17 12:10

Almaz


2 Answers

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

like image 76
Sangeet Suresh Avatar answered Oct 21 '22 08:10

Sangeet Suresh


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
    }
}
like image 28
hannes ach Avatar answered Oct 21 '22 06:10

hannes ach