Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet45/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   41   42   43   44   45   46   47   48   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

36
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
}
}



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   41   42   43   44   45   46   47   48   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling