Pro Android with Kotlin


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

45
CHAPTER 5: Broadcasts
Thread.sleep(3000)
// or real work of course...
Log.e("LOG", "Broadcast done")
}
}
For local broadcasts, the receiver must be declared inside the code. To avoid a resource 
leakage, we create and register the receiver inside onCreate() and unregister it inside 
onDestroy().
class MainActivity : AppCompatActivity() {
private var bcReceiver:BroadcastReceiver? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
bcReceiver = MyReceiver()
val ifi:IntentFilter =
IntentFilter("de.pspaeth.myapp.DO_STH")
LocalBroadcastManager.getInstance(this).
registerReceiver(bcReceiver, ifi)
}
override fun onDestroy() {
super.onDestroy()
// ...
LocalBroadcastManager.getInstance(this).
unregisterReceiver(bcReceiver)
}
}
Explicit Remote Broadcasts
We already pointed out that we can send broadcast messages of the remote type to other 
apps or to the same app where the receivers live. The difference is in how the data is sent. 
For remote messages, the data goes through an IPC channel. Now to send such remote 
broadcast messages to the same app, you write the following:
val intent = Intent(this, MyReceiver::class.java)
intent.action = "de.pspaeth.myapp.DO_STH"
intent.putExtra("myExtra", "myExtraVal")
sendBroadcast(intent)


46
CHAPTER 5: Broadcasts
On the receiving side, for remote messages, the receiver must be declared inside the 
manifest file.

...


"de.pspaeth.myapp.DO_STH">




Looking at the differences between local and remote broadcasts, it is helpful to keep the 
following in mind:


Download 5.42 Mb.

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




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