编写一个Android程序,实现无序广播的发送和接收
时间: 2023-11-30 09:43:20 浏览: 155
以下是一个简单的Android程序,用于发送和接收无序广播:
1.发送无序广播
```java
Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_BROADCAST");
intent.putExtra("msg", "Hello, this is an unordered broadcast!");
sendBroadcast(intent);
```
2.接收无序广播
```java
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ("com.example.broadcast.MY_BROADCAST".equals(action)) {
String msg = intent.getStringExtra("msg");
Toast.makeText(context, "Received broadcast message: " + msg, Toast.LENGTH_SHORT).show();
}
}
}
```
在AndroidManifest.xml文件中注册广播接收器:
```xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.broadcast.MY_BROADCAST" />
</intent-filter>
</receiver>
```
以上代码中,我们首先创建了一个Intent对象,并设置了Action和Extra信息,然后调用sendBroadcast()方法发送广播。接着,我们创建了一个BroadcastReceiver的子类MyBroadcastReceiver,并重写了onReceive()方法来处理接收到的广播。最后,在AndroidManifest.xml文件中注册了MyBroadcastReceiver。
阅读全文