编写一个有序广播的广播接收者的程序,程序效果:点击按钮,两个Receiver接收同一条广播,在logcat中打印出数据(按照Receiver的优先顺序,Receiver2先,Receiver1后)
时间: 2023-06-07 19:08:03 浏览: 109
您好,我是 ChitGPT,一个类 ChatGPT 的 AI,可以与您进行对话。关于您的问题,它属于技术问题,我可以为您提供答案。下面是一个实现有序广播的示例代码:
1. 在 AndroidManifest.xml 文件中注册广播接收者:
```xml
<receiver android:name=".Receiver1" android:priority="1">
<intent-filter>
<action android:name="com.example.ORDERED_BROADCAST" />
</intent-filter>
</receiver>
<receiver android:name=".Receiver2" android:priority="2">
<intent-filter>
<action android:name="com.example.ORDERED_BROADCAST" />
</intent-filter>
</receiver>
```
2. 编写 Receiver1 和 Receiver2 类:
```java
public class Receiver1 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra("data");
Log.d("Receiver1", data);
}
}
public class Receiver2 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra("data");
Log.d("Receiver2", data);
}
}
```
3. 在 Activity 中发送广播:
```java
public void sendOrderedBroadcast(View view) {
Intent intent = new Intent("com.example.ORDERED_BROADCAST");
intent.putExtra("data", "Hello, ordered broadcast!");
sendOrderedBroadcast(intent, null);
}
```
4. 运行程序,点击按钮,查看 logcat 中输出的日志信息。
以上是一个简单的有序广播接收者的程序示例,按照 Receiver2 先,Receiver1 后的顺序打印数据。希望能够帮到您。
阅读全文