android 写一个发送广播接收广播
时间: 2023-08-02 22:31:22 浏览: 75
Android发送广播
好的,以下是一个简单的 Android 发送广播和接收广播的示例代码:
1. 发送广播
```java
Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_BROADCAST");
intent.putExtra("message", "Hello, world!");
sendBroadcast(intent);
```
2. 接收广播
首先,需要在 AndroidManifest.xml 中注册接收器:
```xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.broadcast.MY_BROADCAST" />
</intent-filter>
</receiver>
```
然后,在 MyBroadcastReceiver.java 文件中实现接收器的逻辑:
```java
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.example.broadcast.MY_BROADCAST")) {
String message = intent.getStringExtra("message");
Log.d("MyBroadcastReceiver", "Received message: " + message);
}
}
}
```
这样,当发送广播时,MyBroadcastReceiver 的 onReceive() 方法将被调用并处理接收到的广播。
阅读全文