Tutorials  /  JavaScript

Android BroadcastReceiver Tutorial

Ccentron Redaktion · June 2024 ·3 min read ·JavaScript, 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.
VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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:

Code
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:
Code
<receiver android:name=".ConnectionReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
  1. Programmatically:
Code
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:

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

Sending Broadcast Intents

To send an intent to all related BroadcastReceivers:

Code
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:

Code
<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:

Code
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:

Code
<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:

Code
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.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren