1 基本知识点
1.1 角色:广播发送者、广播接收者
1.2 作用:监听 / 接收 应用发出的广播消息,并做出响应
1.3 原理:设计模式中的观察者模式:基于消息的发布/订阅事件模型
1.4 生命周期:从调用它开始,到onReceiver方法执行完成
2 静态和动态注册
2.1原理:
构建Intent,使用sendBroadcast方法发出广播定义一个广播接收器,该广播接收器继承BroadcastReceiver,并且覆盖onReceive()方法来响应事件注册该广播接收器,我们可以在代码中注册(动态注册),也可以AndroidManifest.xml配置文件中注册(静态注册)。
2.2 动态注册
public class MainActivity extends AppCompatActivity {
DynamicReceiver dynamicReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化IntentFilter对象
IntentFilter filter = new IntentFilter();
filter.addAction("panhouye");
dynamicReceiver = new DynamicReceiver();
//注册广播接收
registerReceiver(dynamicReceiver,filter);
}
//按钮点击事件
public void send2(View v){
Intent intent = new Intent();
intent.setAction("panhouye");
intent.putExtra("sele","潘侯爷");
sendBroadcast(intent);
}
/*动态注册需在Acticity生命周期onPause通过
*unregisterReceiver()方法移除广播接收器,
* 优化内存空间,避免内存溢出
*/
@Override
protected void onPause() {
super.onPause();
//解绑广播
unregisterReceiver(new MyReceiver());
}
//通过继承 BroadcastReceiver建立动态广播接收器
class DynamicReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//通过土司验证接收到广播
Toast t = Toast.makeText(context,"动态广播:"+intent.getStringExtra("sele"),
Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP,0,0);//方便录屏,将土司设置在屏幕顶端
t.show();
}
}
}
2.3 静态注册
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Toast t = Toast.makeText(context,"静态广播:"+intent.getStringExtra("info"), Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP,0,0);
t.show();
}
}
在清单文件manifest下配置
//生成的receiver配置文件
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
//自定义Action
<action android:name="MLY" />
</intent-filter>
</receiver>
public class MainActivity extends AppCompatActivity {
DynamicReceiver dynamicReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//静态广播点击
public void send(View v){
Intent intent = new Intent();
intent.setAction("MLY");
intent.putExtra("info","panhouye");
sendBroadcast(intent);
}
}
3 广播的类型主要分为5类:
普通广播(Normal Broadcast)
系统广播(System Broadcast)
有序广播(Ordered Broadcast)
粘性广播(Sticky Broadcast)
App应用内广播(Local Broadcast)
4 特别注意
4.1 动态广播最好在Activity的onResume()注册、onPause()注销
4.2 静态广播需要在Manifests中注册,动态无需注册