Pro Android with Kotlin



Yüklə 4,6 Kb.
Pdf görüntüsü
səhifə46/231
tarix29.11.2023
ölçüsü4,6 Kb.
#138831
1   ...   42   43   44   45   46   47   48   49   ...   231
@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
}
}



Yüklə 4,6 Kb.

Dostları ilə paylaş:
1   ...   42   43   44   45   46   47   48   49   ...   231




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə