Android编写一个程序,实现无序广播的发送和接收。
时间: 2023-11-30 13:43:41 浏览: 159
以下是Android编写一个程序,实现无序广播的发送和接收的步骤:
1.在AndroidManifest.xml文件中注册广播接收器,例如:
```xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.broadcast.MY_BROADCAST"></action>
</intent-filter>
</receiver>
```
2.创建一个广播接收器类MyBroadcastReceiver,继承BroadcastReceiver类,并重写onReceive()方法,例如:
```java
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 处理接收到的广播信息
String message = intent.getStringExtra("message");
Toast.makeText(context, "Received message: " + message, Toast.LENGTH_SHORT).show();
}
}
```
3.在需要发送广播的地方,创建一个Intent对象,设置广播的Action和需要传递的信息,例如:
```java
Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_BROADCAST");
intent.putExtra("message", "Hello, this is a broadcast message!");
sendBroadcast(intent);
```
4.运行程序,发送广播后,MyBroadcastReceiver类中的onReceive()方法会被调用,处理接收到的广播信息。
阅读全文