|
Pro Android with Kotlin@de android telegram Pro Android with Kotlin Developing Modern Mobile34
CHAPTER 4: Services
class MyService : Service() {
// Binder given to clients
private val binder: IBinder = MyBinder(this)
// Random number generator
private val generator: Random = Random()
override
fun onBind(intent: Intent):IBinder {
return binder
}
/** method for clients */
fun getRandomNumber():Int {
return generator.nextInt(100)
}
}
To bind to this service internally, from the same app, inside the service using the client, write
the following:
val servcConn = object : ServiceConnection {
override
fun onServiceDisconnected(compName: ComponentName?) {
Log.e("LOG","onServiceDisconnected: " + compName)
}
override
fun onServiceConnected(compName: ComponentName?,
binder: IBinder?) {
Log.e("LOG","onServiceConnected: " + compName)
val servc = (binder as MyBinder).getService()
Log.i("LOG", "Next random number from service: " +
servc.getRandomNumber())
}
override
fun onBindingDied(compName:ComponentName) {
Log.e("LOG","onBindingDied: " + compName)
}
}
val intent = Intent(this, MyService::class.java)
val flags = BIND_AUTO_CREATE
bindService(intent, servcConn, flags)
Here, the
object: ServiceConnection {...}
construct is the Kotlin way of implementing an
interface by creating an object of an anonymous inner class, like
new ServiceConnection()
{...}
in Java. The construct is called an
object expression
in Kotlin. The
this
inside the
intent constructor in this case refers to a
Context
object. You can use it like this inside an
activity. If you have the
Context
in a variable instead, use that variable’s name here.
Of course, instead of the logging, you should do more meaningful things. Especially inside
the
onSeviceConnected()
method you can save the binder or service in a variable for further
use. Just make sure, having said all that, that you appropriately react to a died binding or a
killed service connection. You could, for example, try to bind the service again, tell the user,
or both.
|
|
|