In Android, a BroadcastReceiver is used to listen for broadcast messages, which are often sent by the system or other applications to notify your application about events like connectivity changes, battery level changes, or custom messages. The BroadcastReceiver listens for these broadcasts and performs an action based on them.
Example of Using a BroadcastReceiver in Android
Let’s go through an example of how to use a BroadcastReceiver to listen for a system broadcast, such as when the device's battery level changes.
Step 1: Create the BroadcastReceiver
First, you need to create a subclass of BroadcastReceiver. This class will override the onReceive() method, which will be triggered whenever the broadcast event occurs.
Here’s an example of a simple BroadcastReceiver that listens for changes in the battery level:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.util.Log;
public class BatteryReceiver extends BroadcastReceiver {
// This method will be called when a broadcast matching the registered filter is received
@Override
public void onReceive(Context context, Intent intent) {
// Check if the broadcast is related to battery status
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
// Get the current battery level from the broadcast intent
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
// Log the battery level for demonstration purposes
Log.d("BatteryReceiver", "Battery Level: " + level + "%");
}
}
}
In the onReceive() method, we check if the action of the received broadcast is Intent.ACTION_BATTERY_CHANGED, which is a system broadcast sent when the battery level changes. We then retrieve the battery level using intent.getIntExtra() and log it.
Step 2: Register the BroadcastReceiver
There are two ways to register a BroadcastReceiver in Android: statically in the AndroidManifest.xml file, or dynamically at runtime. In this example, we’ll use dynamic registration.
Here’s how to register the BroadcastReceiver in your MainActivity:
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// Declare the receiver as an instance variable
private BatteryReceiver batteryReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the receiver
batteryReceiver = new BatteryReceiver();
// Create an IntentFilter to listen for battery level changes
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
// Register the receiver with the filter
registerReceiver(batteryReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregister the receiver when the activity is destroyed
unregisterReceiver(batteryReceiver);
}
}
In the onCreate() method, we create an IntentFilter for the action Intent.ACTION_BATTERY_CHANGED (which is broadcasted when the battery level changes). Then, we register the BatteryReceiver using the registerReceiver() method.
It’s important to unregister the receiver when it's no longer needed, such as when the activity is destroyed. In this case, we do that in the onDestroy() method by calling unregisterReceiver().
Step 3: Test the BroadcastReceiver
Now, when the battery level changes, your BroadcastReceiver will log the battery level to the console using Log.d().
To test this, you can either:
- Disconnect and reconnect the charger to trigger the change in battery level.
- Use a physical or virtual Android device and see the logs using Logcat in Android Studio.
Important Considerations
-
Permissions: For many system broadcasts (e.g., listening for SMS, network changes), you need to declare the necessary permissions in your
AndroidManifest.xml. For battery-related events, no special permissions are required.<uses-permission android:name="android.permission.BATTERY_STATS" /> -
Unregistering the Receiver: Always ensure you unregister the receiver when it's no longer needed, especially for dynamically registered receivers, to avoid memory leaks.
-
Handling Multiple Broadcasts: You can register multiple receivers with different filters. For example, you could register a receiver to listen for Wi-Fi state changes, incoming SMS, or even custom broadcasts.
Example of a Complete Application:
Here is the complete example with the BroadcastReceiver to listen for battery changes.
BatteryReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.util.Log;
public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Action when the battery level changes
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
Log.d("BatteryReceiver", "Battery Level: " + level + "%");
}
}
}
MainActivity.java
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private BatteryReceiver batteryReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the receiver
batteryReceiver = new BatteryReceiver();
// Register the receiver for battery level changes
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregister the receiver when activity is destroyed
unregisterReceiver(batteryReceiver);
}
}
Conclusion
In this example, we’ve created a BroadcastReceiver to listen for the battery level change and log it using Log.d(). This example shows the steps to create, register, and unregister a BroadcastReceiver in an Android application. You can customize this approach to listen for other system or custom broadcasts to add more functionality to your app.
0 Comments