Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

Broadcast Receiver in Android With Example

A BroadcastReceiver in Android is a component that allows your app to register for system or application events. Apps can also initiate broadcasts, both within the same app and to other apps.

Here's a step-by-step guide to understanding and implementing a BroadcastReceiver:

1. Define a BroadcastReceiver:

First, you'll define a BroadcastReceiver by subclassing BroadcastReceiver:

class MyReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == "com.example.MY_ACTION") {
            Toast.makeText(context, "Received a custom broadcast!", Toast.LENGTH_SHORT).show()
        }
    }
}

In the onReceive() method, you can check the intent's action and respond accordingly.

2. Register the BroadcastReceiver:

There are two ways to register a BroadcastReceiver:

  • Manifest-declared: You can declare your BroadcastReceiver in the AndroidManifest.xml:

    <receiver android:name=".MyReceiver">
        <intent-filter>
            <action android:name="com.example.MY_ACTION" />
        </intent-filter>
    </receiver>
    

    With manifest-declared receivers, the system can start up your app to handle a broadcast, even if the app is not currently running.

  • Dynamically in code: Register your BroadcastReceiver using registerReceiver():

    val receiver = MyReceiver()
    val filter = IntentFilter("com.example.MY_ACTION")
    registerReceiver(receiver, filter)
    

    When registering dynamically, the BroadcastReceiver only receives broadcasts as long as its registering context (usually an activity) is alive. If you register it in an Activity, it won't receive broadcasts when the activity is paused or stopped.

3. Sending Broadcasts:

You can send a broadcast using an Intent:

val intent = Intent("com.example.MY_ACTION")
sendBroadcast(intent)

4. Unregister BroadcastReceiver:

If you've registered the BroadcastReceiver dynamically, make sure to unregister it when it's no longer needed, usually in the corresponding lifecycle method like onPause or onDestroy:

unregisterReceiver(receiver)

Note:

  1. For system-wide broadcasts, using the manifest to register receivers has been discouraged from Android Oreo (API 26) onwards due to background execution limits.

  2. Always be cautious about which broadcasts your app sends. If other apps can listen for your broadcasts, sensitive data can be read, or apps can exploit your broadcasts in unintended ways.

  3. Starting from Android Q (API 29), apps targeting the new platform can no longer use the sendBroadcast(Intent) method to send regular local broadcasts.

In summary, a BroadcastReceiver allows apps to respond to broadcast messages from the system or other apps, making it a valuable tool for many common Android tasks. Always consider the lifecycle of your receivers and the types of broadcasts you're working with to ensure a responsive and well-behaving app.

  1. Registering a BroadcastReceiver dynamically in Android:

    • Description: A BroadcastReceiver can be registered dynamically in code, allowing flexibility in responding to events based on app logic or user interactions.
    • Code (Kotlin):
      val filter = IntentFilter("com.example.CUSTOM_ACTION")
      val receiver = MyReceiver()
      registerReceiver(receiver, filter)
      
  2. Broadcast Receiver for system events in Android:

    • Description: Use a BroadcastReceiver to respond to system events, such as battery level changes, device boot, or screen on/off. This allows your app to react to important system-wide changes.
    • Code (Kotlin):
      class SystemEventReceiver : BroadcastReceiver() {
          override fun onReceive(context: Context?, intent: Intent?) {
              when (intent?.action) {
                  Intent.ACTION_BOOT_COMPLETED -> {
                      // Handle device boot
                  }
                  // Handle other system events
              }
          }
      }
      
  3. Broadcast Receiver for custom events in Android:

    • Description: Define custom actions and use a BroadcastReceiver to handle these events within your app. This allows different components of your app to communicate and respond to specific custom triggers.
    • Code (Kotlin):
      // Sender
      val intent = Intent("com.example.CUSTOM_ACTION")
      sendBroadcast(intent)
      
      // Receiver
      class CustomEventReceiver : BroadcastReceiver() {
          override fun onReceive(context: Context?, intent: Intent?) {
              // Handle custom event
          }
      }
      
  4. Working with Intent Filters in BroadcastReceiver Android:

    • Description: Intent filters define the types of broadcasts a BroadcastReceiver can handle. By specifying actions, categories, and data types in the filter, you determine which broadcasts trigger the receiver.
    • Code (Kotlin):
      <receiver android:name=".MyReceiver">
          <intent-filter>
              <action android:name="android.intent.action.AIRPLANE_MODE"/>
              <category android:name="android.intent.category.DEFAULT"/>
          </intent-filter>
      </receiver>
      
  5. Broadcast Receiver for network state changes in Android:

    • Description: Use a BroadcastReceiver to monitor changes in network connectivity, such as when the device switches between mobile data and Wi-Fi. This can be useful for adapting app behavior based on the current network state.
    • Code (Kotlin):
      class NetworkStateReceiver : BroadcastReceiver() {
          override fun onReceive(context: Context?, intent: Intent?) {
              if (intent?.action == ConnectivityManager.CONNECTIVITY_ACTION) {
                  // Handle network state change
              }
          }
      }
      
  6. Sending and receiving broadcasts in Android:

    • Description: An app can send broadcasts using sendBroadcast(Intent), and BroadcastReceiver components can receive and respond to these broadcasts. This communication mechanism allows different parts of an app or even different apps to interact.
    • Code (Kotlin):
      // Sender
      val intent = Intent("com.example.CUSTOM_ACTION")
      sendBroadcast(intent)
      
      // Receiver
      class CustomReceiver : BroadcastReceiver() {
          override fun onReceive(context: Context?, intent: Intent?) {
              // Handle broadcast
          }
      }