Pro Android with Kotlin


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

44
CHAPTER 5: Broadcasts
Explicit Broadcasts
An explicit broadcast is a broadcast published in such a way that there is exactly one 
receiver addressed by it. This usually makes sense only if both broadcast publishers and 
subscribers are part of the same app or, less frequently, part of the same app collection if 
there is a strong functional dependency among them.
There are differences between local and remote broadcasts: local broadcast receivers 
must reside in the same app, they run fast, and receivers cannot be declared inside 
AndroidManifest.xml. Instead, a programmatical registration method must be used for local 
broadcast receivers. Also, you must use the following to send local broadcast messages:
// send local broadcast
LocalBroadcastManager.getInstance(Context).
sendBroadcast(...)
Remote broadcast receivers, on the other hand, can reside in the same app, they are slower, 
and it is possible to use AndroidManifest.xml to declare them. To send remote broadcasts, 
you write the following:
// send remote broadcast (this App or other Apps)
sendBroadcast(...)
Explicit Local Broadcasts
To send a local broadcast message to a local broadcast receiver inside the same app, you 
write the following:
val intent = Intent(this, MyReceiver::class.java)
intent.action = "de.pspaeth.simplebroadcast.DO_STH"
intent.putExtra("myExtra", "myExtraVal")
Log.e("LOG", "Sending broadcast")
LocalBroadcastManager.getInstance(this).
sendBroadcast(intent)
Log.e("LOG", "Broadcast sent")
Here, MyReceiver is the receiver class.
class MyReceiver : BroadcastReceiver() {
override
fun onReceive(context: Context?, intent: Intent?) {
Toast.makeText(context, "Intent Detected.",
Toast.LENGTH_LONG).show()
Log.e("LOG", "Received broadcast")
Note Local broadcasts should be favored over remote broadcasts for performance reasons. The 
apparent disadvantage of not being able to use AndroidManifest.xml to declare local receivers 
does not matter too much, since starting with Android 8.0 (API level 26) the use cases of declaring 
broadcast receivers inside the manifest files are limited anyway.



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   45   46   47   48   49   50   51   52   ...   223




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