Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Android BroadcastReceiver Tutorial

Learn how to handle system-wide events in your application with Android BroadcastReceiver. Our tutorial will guide you step-by-step on how to create and register a BroadcastReceiver. Start now and make your app more responsive!

What is an Android BroadcastReceiver?

An Android BroadcastReceiver is a dormant component that listens for system-wide broadcast events or intents. When one of these events occurs, the BroadcastReceiver activates the application by either creating a status bar notification or performing a task. Unlike Activities, a BroadcastReceiver has no user interface. It delegates tasks to services based on the received intents.

Important System Intents

Some important system-wide intents are:

  • android.intent.action.BATTERY_LOW: Indicates low battery level.
  • android.intent.action.BOOT_COMPLETED: Sent after the system finishes booting.
  • android.intent.action.CALL: Makes a call.
  • android.intent.action.DATE_CHANGED: Date has changed.
  • android.intent.action.REBOOT: Device is rebooting.
  • android.net.conn.CONNECTIVITY_CHANGE: Network connection has changed or reset.

Setting up a BroadcastReceiver in Android

To set up a BroadcastReceiver, two steps are required:

  1. Creating a BroadcastReceiver
  2. Registering the BroadcastReceiver

Creating a BroadcastReceiver

An example of implementing a BroadcastReceiver:

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();
    }
}

The BroadcastReceiver is an abstract class, and the onReceive() method is called when an event occurs. The intent object contains all the additional data.

Registering the BroadcastReceiver

A BroadcastReceiver can be registered in two ways:

  1. In the AndroidManifest.xml:

<receiver android:name=".ConnectionReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

  1. Programmatically:

IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);

To deactivate a BroadcastReceiver in the onStop() or onPause() of the Activity, use:

@Override
protected void onPause() {
    unregisterReceiver(myReceiver);
    super.onPause();
}

Sending Broadcast Intents

To send an intent to all related BroadcastReceivers:

Intent intent = new Intent();
intent.setAction("com.journaldev.CUSTOM_INTENT");
sendBroadcast(intent);

Don’t forget to add the above action in the intent filter of the manifest or programmatically.

Example of an Android Application

Here is an example of an application that listens for network changes and processes a custom intent:

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Broadcast"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity {
    ConnectionReceiver receiver;
    IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receiver = new ConnectionReceiver();
        intentFilter = new IntentFilter("com.journaldev.broadcastreceiver.SOME_ACTION");
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    public void someMethod(View view) {
        Intent intent = new Intent("com.journaldev.broadcastreceiver.SOME_ACTION");
        sendBroadcast(intent);
    }
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.journaldev.broadcastreceiver">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".ConnectionReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

ConnectionReceiver.java:

public class ConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals("com.journaldev.broadcastreceiver.SOME_ACTION"))
            Toast.makeText(context, "SOME_ACTION is received", Toast.LENGTH_LONG).show();
        else {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork isConnectedOrConnecting();
            Toast.makeText(context, isConnected ? "Network is connected" : "Network is changed or reconnected", Toast.LENGTH_LONG).show();
        }
    }
}

Conclusion

With this knowledge, you can now create your own BroadcastReceivers and integrate them into your Android applications. These allow you to respond to system-wide events and act accordingly.

Boost Your App's Responsiveness with Our Cloud Services!

Ready to take your Android app to the next level? Sign up for our cloud services trial and experience seamless integration with Android BroadcastReceiver. Enhance your app's performance and responsiveness with our cutting-edge cloud solutions. Start your free trial today and see the difference!

Try for free!