android 写一个发送广播接收广播
时间: 2023-08-02 11:32:53 浏览: 54
好的,以下是一个简单的Android发送广播和接收广播的示例代码:
发送广播:
```java
Intent intent = new Intent();
intent.setAction("com.example.MY_ACTION");
intent.putExtra("message", "Hello, broadcast!");
sendBroadcast(intent);
```
在这个例子中,我们创建了一个Intent对象,并设置了一个自定义的Action和一个消息。然后我们通过调用sendBroadcast()方法发送广播。
接收广播:
```java
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.MY_ACTION");
registerReceiver(myReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
```
在这个例子中,我们创建了一个BroadcastReceiver对象来接收广播。我们重写了onReceive()方法,在方法中获取了广播中的消息,并显示了一个Toast。然后我们在Activity的onResume()方法中注册了我们的广播接收器,并在onPause()方法中取消注册。我们还创建了一个IntentFilter来指定我们要接收哪些广播。
希望这个例子能够帮助你了解如何在Android中发送和接收广播。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)