建立 BroadcastReceiver 的操作步骤
时间: 2024-03-03 13:25:59 浏览: 64
建立 BroadcastReceiver 的操作步骤如下:
1. 创建一个类并继承 BroadcastReceiver。
2. 重写 onReceive() 方法,该方法将在广播消息到达时被调用。
3. 在 AndroidManifest.xml 文件中注册 BroadcastReceiver,指定要接收的广播类型和权限等信息。
4. 在应用程序中发送广播消息,可以使用 sendBroadcast()、sendOrderedBroadcast() 或 sendStickyBroadcast() 等方法。
以下是一个简单的 BroadcastReceiver 示例代码:
```java
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 处理接收到的广播消息
String action = intent.getAction();
if (action.equals("com.example.broadcast.MY_BROADCAST")) {
// 处理自定义广播消息
String message = intent.getStringExtra("message");
Log.d("MyBroadcastReceiver", "Received message: " + message);
} else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
// 处理系统广播消息
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryLevel = level / (float) scale;
Log.d("MyBroadcastReceiver", "Battery level: " + batteryLevel);
}
}
}
```
在 AndroidManifest.xml 中注册 BroadcastReceiver:
```xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.broadcast.MY_BROADCAST" />
<action android:name="android.intent.action.BATTERY_CHANGED" />
</intent-filter>
</receiver>
```
在应用程序中发送广播消息:
```java
Intent intent = new Intent("com.example.broadcast.MY_BROADCAST");
intent.putExtra("message", "Hello, world!");
sendBroadcast(intent);
```
阅读全文