android 广播通知,Android 开发(10)ActionBar & 消息 & 通知 & 广播全在这篇!
时间: 2024-03-10 09:47:30 浏览: 23
好的,你的问题是关于 Android 广播通知的。那么,我可以告诉你在 Android 开发中如何使用广播通知。
在 Android 中,广播通知是一种机制,可以让应用程序中的组件(如 Activity、Service、BroadcastReceiver 等)之间进行通信。广播通知可以被发送和接收,并可以在系统范围内或应用程序范围内进行传递。
要发送广播通知,可以使用 Intent 对象,并使用 sendBroadcast() 方法将其发送。要接收广播通知,可以创建一个 BroadcastReceiver,并使用 registerReceiver() 方法进行注册,在接收到广播通知时,会调用 BroadcastReceiver 的 onReceive() 方法。
例如,以下代码演示了如何发送一个自定义广播通知:
```
Intent intent = new Intent();
intent.setAction("com.example.MY_CUSTOM_ACTION");
intent.putExtra("data", "Hello, world!");
sendBroadcast(intent);
```
接下来,以下代码演示了如何创建一个 BroadcastReceiver 并注册接收自定义广播通知:
```
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("com.example.MY_CUSTOM_ACTION")) {
String data = intent.getStringExtra("data");
Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
}
}
}
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter("com.example.MY_CUSTOM_ACTION");
registerReceiver(receiver, filter);
```
这样,当发送一个自定义广播通知时,MyReceiver 的 onReceive() 方法将被调用,并在屏幕上显示 "Hello, world!" 的 Toast 消息。
希望这个例子可以帮助你了解如何在 Android 中使用广播通知。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)