Broadcast Receiver in Android

Overview

Broadcasts are messaging components that are used to communicate between different applications and Android system. These communication happens when there is an even of interest occurs. Broadcast receivers are the ones that is used to receive these broadcasts and act accordingly. Broadcast receiver is actually an abstract class where you have to implement onReceive(context Context, intent Intent) method.
There are two types of Broadcast Receivers
  • Static Broadcast Receivers
    • The broadcast receiver that you define in AndroidManifest.xml file.
 <receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"
tools:ignore="BatteryLife" />
</intent-filter>
</receiver>
  • Dynamic Broadcast Receivers
    • The custom broadcast that you make programmatically using 
 class MyBroadcastReceiver : BroadcastReceiver()
{
override fun onReceive(context : Context , intent : Intent)
{
if (Intent.ACTION_BOOT_COMPLETED == intent.action)
{
Toast.makeText(context , "Boot Completed" , Toast.LENGTH_LONG).show()
}
if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action)
{
Toast.makeText(context , "Connection Issue" , Toast.LENGTH_LONG).show()
}
}
}

Do's and Dont's

  • You should register a broadcast receiver in onResume() lifecycle.
 override fun onResume()
{
super.onResume()
val intentFilter = IntentFilter()
intentFilter.addAction(packageName + "android.net.conn.CONNECTIVITY_CHANGE")
intentFilter.addAction(packageName + "android.intent.action.BOOT_COMPLETED")
registerReceiver(myBroadcastReceiver, intentFilter)
}
  • Don't forget to unregister the receiver in onPause(), onStop() or onDestroy() lifecycle.
 override fun onPause()
{
super.onPause()
unregisterReceiver(myBroadcastReceiver)
}

Reference



Comments

Popular posts from this blog

SSLSocketFactory in Android

Architecture Components in Android

DataBinding in Android