Pro Android with Kotlin


Local explicit broadcasts


Download 5.42 Mb.
Pdf ko'rish
bet51/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   47   48   49   50   51   52   53   54   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

Local explicit broadcasts:
The sender uses an explicit receiver class, the receiver must be 
declared programmatically, and both the sender and receiver use 
LocalBroadcastManager to send messages and to register the receiver.

Remote explicit broadcasts:
The sender uses explicit receiver class, and the receiver must be declared 
in AndroidManifest.xml.
For the class that is responsible for handling received broadcasts, there is no difference 
compared to the explicit local broadcasts.
class MyReceiver : BroadcastReceiver() {
override
fun onReceive(context: Context?, intent: Intent?) {
// handle incoming broadcasts...
}
}
Explicit Broadcasts Sending to Other Apps
The senders and receivers of explicit broadcasts can live in different apps. For this to work
you can no longer use the intent constructor we used earlier.
val intent = Intent(this, MyReceiver::class.java)
intent.action = "de.pspaeth.myapp.DO_STH"
// add other coords...
sendBroadcast(intent)


47
CHAPTER 5: Broadcasts
This is because the receiving class, here MyReceiver, is not part of the classpath. There is, 
however, another construct we can use instead.
val intent = Intent()
intent.component = ComponentName("de.pspaeth.xyz",
"de.pspaeth.xyz.MyReceiver")
intent.action = "de.pspaeth.simplebroadcast.DO_STH"
// add other coords...
sendBroadcast(intent)
Here, the first argument to ComponentName is the package string of the receiving package
and the second argument is the class name.
Implicit Broadcasts
Implicit broadcasts are broadcasts with an undefined number of possible receivers. For 
explicit broadcasts, you learned that we had to build the corresponding intents by using 
the constructor that points to the recipient component: val intent = Intent(this, 
TheReceiverClass::class.java). Contrary to that, for implicit broadcast we no longer 
specify the recipient but instead give hints on which components might be interested in 
receiving it. Here’s an example:
val intent = Intent()
intent.action = "de.pspaeth.myapp.DO_STH"
sendBroadcast(intent)
Here, we actually express the following: “Send a broadcast message to all receivers that 
are interested in action de.pspaeth.myapp.DO_STH.” The Android OS determines which 
components are eligible to receive such broadcast messages then; this might result in zero, 
one, or many actual recipients.
There are three decisions you must make before you start programming implicit broadcasts.


Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   47   48   49   50   51   52   53   54   ...   223




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