|
Pro Android with Kotlin@de android telegram Pro Android with Kotlin Developing Modern Mobile36
CHAPTER 4: Services
To bind to an external service, in other words, a service belonging to another app, you
cannot use the same binding technique as described for internal services. The reason for
this is the
IBinder
interface we are using cannot directly access the service class since
the class is not visible across process boundaries. We can, however, wrap data to be
transported between the service and the service client into an
android.os.Handler
object
and use this object to send data from the service client to the service. To achieve this, for the
service we first need to define a
Handler
for receiving messages. Here’s an example:
internal class InHandler(val ctx: Context) : Handler() {
override
fun handleMessage(msg: Message) {
val s = msg.data.getString("MyString")
Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show()
}
}
[...]
class MyService : Service() {
val myMessg:Messenger = Messenger(InHandler(this))
[...]
}
Instead of just creating a
Toast
message, you can of course do more interesting things
when a message arrives. Now in the service’s
onBind()
method, we return the binder object
provided by the messenger.
override
fun onBind(intent:Intent):IBinder {
return myMessg.binder
}
As for the entries inside the
AndroidManifest.xml
file, we can write the same as when
starting
remote services.
In the service client, you’d add a
Messenger
attribute and a
ServiceConnection
object. Here’s
an example:
var remoteSrvc:Messenger? = null
private val myConnection = object : ServiceConnection {
override
fun onServiceConnected(className: ComponentName,
service: IBinder) {
remoteSrvc = Messenger(service)
}
override
fun onServiceDisconnected(className: ComponentName) {
remoteSrvc = null
}
}
|
|
|