安卓广播实例
时间: 2023-08-17 10:04:03 浏览: 50
下面是一个简单的安卓广播实例:
1. 创建一个自定义广播接收器类:
```java
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && action.equals("com.example.mybroadcastreceiver.ACTION")) {
String message = intent.getStringExtra("message");
Log.d(TAG, "Received message: " + message);
Toast.makeText(context, "Received message: " + message, Toast.LENGTH_SHORT).show();
}
}
}
```
2. 在 AndroidManifest.xml 文件中声明广播接收器:
```xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.mybroadcastreceiver.ACTION" />
</intent-filter>
</receiver>
```
3. 发送广播:
```java
Intent intent = new Intent("com.example.mybroadcastreceiver.ACTION");
intent.putExtra("message", "Hello, world!");
sendBroadcast(intent);
```
以上代码会发送一个自定义广播,然后通过 MyBroadcastReceiver 接收并处理该广播,最后在日志和 Toast 中显示接收到的消息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)