BroadCastReceiver
一.BroadCastReceiver介绍:
BroadCastReceiver广播接受者,安卓四大组件之一
广播三要素:
(1)广播发送者 : 发送广播
(2)广播接收者(调频): 用于接收广播
(3)要处理的事情 :处理广播的相关信息, Intent有图对象
广播的使用场景:
(1)同一APP下多个组件之间传递数据(Activity/Fragment/Service之间传递数据)
(2)2个APP之间传递数据
技能get点:
(1)自定义广播接受者
(2)使用广播接受者进行电话拦截和短信拦截和系统电量的变化
二.如何实现广播
步骤1:广播接受者
(1)自定义类继承BroadcastReceiver,重写onReceive方法
(2)注册广播(安卓的四大组件都需要注册)
静态注册:在清单文件中
动态注册:在代码中注册(注册和解除注册)
步骤2:广播发送方:sendBroadcast(Intent意图对象)
静态注册和动态注册的区别:假如说Activity是接受者:
动态注册:
(1)广播会跟Activity的生命周期的结束而结束;
(2)自由的控制注册和取消,有很大的灵活性
静态注册:
(1)广播不会跟随Activity的生命周期的结束而结束,一直存在,即使应用程序关闭,也会被唤醒接受广播
(2)全局的广播
三.代码案例
(1).自定义广播接收者类继承BroadCastReceiver,重写onReceiver方法
1
2
3
4
5
6
7
8
9
10
11
12
13public class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //TODO 1:获取action String action = intent.getAction(); if("android.broad.action.customer".equals(action)){ Bundle bundle = intent.getExtras(); int msg=bundle.getInt("msg"); Log.i("广播", "接受到了一个广播: "+msg); } } }
(2).注册广播方式一:清单文件静态注册
1
2
3
4
5
6
7<!--收音机--> <receiver android:name=".MyReceiver"> <!--调频--> <intent-filter> <action android:name="android.broad.action.customer" /> </intent-filter> </receiver>
(3)注册广播方式二:动态注册
onCreate():注册广播调用Context的registerReceiver()方法
onDestory():解除注册调用Context的unregisterReceiver()方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23public class MainActivity extends AppCompatActivity { private MyReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); receiver=new MyReceiver(); regeister();//注册广播 } private void regeister() { //TODO 1:创建过滤器 IntentFilter intentFilter=new IntentFilter(); //TODO 2:调频: intentFilter.addAction("android.broad.action.customer"); //TODO 3:注册: 给这个Activity注册 registerReceiver(receiver,intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver);//解除注册 } }
(4)发送方:sendBroad(Intent意图对象)
1
2
3
4
5
6
7
8
9//按钮的点击事件 public void customer(View view) { Intent intent=new Intent(); intent.setAction("android.broad.action.customer"); Bundle bundle=new Bundle(); bundle.putString("msg","发送广播"); intent.putExtras(bundle); sendBroadcast(intent); }
四.广播的分类:
1.无序广播:sendBroadcast()
2.有序广播:sendOrderBroadcast()
当发送的是有序广播的时候,优先级越高的接收者越先接收到广播,可以调用abortBroadCast()中断广播,不让其他人接收广播
3.粘性广播:sendStickyBroadcast()
将之前广播发送方发送的消息存储起来,普通广播不能接收之前发过的消息
更多的广播
1:来电广播
(1)添加权限:android.permission.READ_PHONE_STATE
(2)注册广播(这里用的是动态广播)
(3)创建接受广播对象
mIncomingNumber = intent.getStringExtra(“incoming_number”);来电号码
(4).注销掉广播对象
2.电量变化监听
Intent.ACTION_BATTERY_CHANGED:充电状态,或者电池的电量发生变化
Intent.ACTION_BATTERY_LOW:电池电量低
Intent.ACTION_BATTERY_OKAY:电池电量充足
3.接收锁屏亮度广播
ACTION_SCREEN_ON:亮屏
ACTION_SCREEN_OFF:锁屏
最后
以上就是落寞咖啡豆最近收集整理的关于BroadCastReceiver广播BroadCastReceiver的全部内容,更多相关BroadCastReceiver广播BroadCastReceiver内容请搜索靠谱客的其他文章。
发表评论 取消回复