Pro Android with Kotlin


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

37
CHAPTER 4: Services
To actually perform the binding, you can proceed like for internal services. For example, 
inside an activity’s onCreate() method, you could write the following:
val intent:Intent = Intent("
.START_SERVICE")
intent.setPackage("
")
bindService(intent, myConnection, Context.BIND_AUTO_CREATE)
Here, substitute the service package’s name for 
 appropriately.
Now to send a message from the client to the service across the process boundary, you can 
write the following:
val msg = Message.obtain()
val bundle = Bundle()
bundle.putString("MyString", "A message to be sent")
msg.data = bundle
remoteSrvc?.send(msg)
Note that for this example you cannot add these lines into the activity’s onCreate() 
method after the bindService() statement because remoteSrvc gets a value only after the 
connection fires up. But you could, for example, add it to the onServiceConnected() method 
of the ServiceConnection class.
Note In the previous code, no precautions were taken to ensure connection sanity. You should add 
sanity checks for productive code. Also, unbind from the service inside the onStop() method.
Data Sent by Services
Up to now we were talking of messages sent from the service client to the service. Sending 
data in the opposite direction, from the service to the service client, is possible as well; it can 
best be achieved by using an extra Messenger inside the client, a broadcast message, or a 
ResultReceiver class.
For the first method, provide another Handler and Messenger in the service client, and once 
the client receives an onServiceConnected() callback, send a Message to the service with the 
second Messenger passed by the replyTo parameter.
internal class InHandler(val ctx: Context) : Handler() {
override
fun handleMessage(msg: Message) {
// do something with the message from the service
}
}
class MainActivity : AppCompatActivity() {
private var remoteSrvc:Messenger? = null
private var backData:Messenger? = null



Download 5.42 Mb.

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




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