90 lines
1.8 KiB
Markdown
90 lines
1.8 KiB
Markdown
|
## 第8章:广播机制
|
|||
|
|
|||
|
1.广播是一种不同组件之间进行通信的机制
|
|||
|
|
|||
|
2.Android系统的四大组件:`Activity` `ContentProvider` `BroadcastReceiver` `Service`
|
|||
|
|
|||
|
3.广播机制的实现流程
|
|||
|
|
|||
|
广播发送者 AMS 广播接收者
|
|||
|
|
|||
|
4.(掌握)广播接受者的创建 new other BroadcastReceiver
|
|||
|
|
|||
|
5.(掌握)广播接收者的注册:动态注册 静态注册
|
|||
|
|
|||
|
|
|||
|
|
|||
|
案例:ForHelp
|
|||
|
|
|||
|
(1)创建项目
|
|||
|
|
|||
|
(2)复制照片和布局文件
|
|||
|
|
|||
|
(3)创建广播接收者new--other--BroadcastReceiver
|
|||
|
|
|||
|
清单文件中静态注册广播接收者的代码:
|
|||
|
|
|||
|
```xml
|
|||
|
<receiver
|
|||
|
android:name=".MyReceiver"
|
|||
|
android:enabled="true"
|
|||
|
android:exported="true"></receiver>
|
|||
|
```
|
|||
|
|
|||
|
(4)MainActivity中:
|
|||
|
|
|||
|
发送广播
|
|||
|
|
|||
|
动态注册广播接收者
|
|||
|
|
|||
|
取消注册广播接收者
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
## 广播的类型
|
|||
|
|
|||
|
1.无序广播 所有的广播接收者都能接收广播,但是接受的顺序不确定。ForHelp
|
|||
|
|
|||
|
核心功能:
|
|||
|
|
|||
|
发送广播 sendBroadcast(intent)
|
|||
|
|
|||
|
注册广播接收者 registerReceiver(receiver,intentFilter)
|
|||
|
|
|||
|
2.有序广播 优先级较高的接收者先接收广播,如果该接收者对广播进行拦截,后面的接收者就接收不到广播了
|
|||
|
|
|||
|
核心功能:
|
|||
|
|
|||
|
发送广播 sendOrderedBroadcast(intent)
|
|||
|
|
|||
|
注册广播接收者 registerReceiver(receiver,intentFilter)
|
|||
|
|
|||
|
设置广播接收者的优先级 intentFilter.setPriority(1000)
|
|||
|
|
|||
|
拦截广播 abortBoradcast();
|
|||
|
|
|||
|
|
|||
|
|
|||
|
案例2
|
|||
|
|
|||
|
(1)创建项目
|
|||
|
|
|||
|
(2)复制图片和布局文件
|
|||
|
|
|||
|
(3)创建三个广播接收者
|
|||
|
|
|||
|
(4)MainActivity组件中
|
|||
|
|
|||
|
发送有序广播
|
|||
|
|
|||
|
动态注册三个广播接收者
|
|||
|
|
|||
|
设置某个广播接收者一定能接收到广播
|
|||
|
|
|||
|
sendOrderedBroadcast(intent,null,new MyReceiver3(),null,0,null,null);
|
|||
|
|
|||
|
当没有设置广播接收者优先级的时候,是按照注册的顺序来接收的。
|