BroadcastReceiver广播接收者

 动态注册和静态注册两种方法,动态注册是程序运行时才接收广播,静态注册不管程序是否运行,都会接收广播!!

  如果是接收系统的广播,很多都是需要加上权限的!!!


	首先需要继承BroadcastReceive类,重写父类的onReceive方法,当发送广播时就会调用该方法:

public class MyBroadcast extends BroadcastReceiver{
    @Override//收到广播就会回调该方法
    public void onReceive(Context context, Intent intent) {  Intent参数为发送过来的数据

        Bundle bundle=intent.getExtras();
        String str=bundle.getString("mm");
        Toast.makeText(context,"广播接收者1号的内容为:"+str,Toast.LENGTH_LONG).show();
    }
}
  其中,广播接收者在接收有序广播时,可以拦截广播:   调用父类的abortBroadcast方法



  1、静态注册广播接收者,在项目清单文件中:
   <!-- 广播注册 -->
        <receiver android:name=".MyBroadcast">
            <intent-filter android:priority="1">
                <!-- 自定义频道 (要接收的频道,可以是系统的)-->
                <action android:name="mma" />
            </intent-filter>
        </receiver>
        
        
 其中,意图过滤器的 android:priority属性用来设置优先级(1---1000)(接收有序广播时可以用)
<intent-filter android:priority="500">


2、动态注册广播接收者,JAVA代码:
<span style="white-space:pre">	</span>MyBroadcast broadcast=new MyBroadcast();  创建广播接受者对象
        IntentFilter filter=new IntentFilter("mma");  创建意图过滤器,参数为接收的频道
        registerReceiver(broadcast,filter);      注册

注意:动态注册广播接收者,需要取消注册:
  最好是在当前Activity的onDestroy方法中取消注册,调用上下文的unregisterReceiver方法
   @Override//退出活动时调用(销毁活动)
    protected void onDestroy() {
        super.onDestroy();
        //取消注册
        unregisterReceiver(myBroadcast1);
        unregisterReceiver(myBroadcast2);
        unregisterReceiver(myBroadcast3);
        unregisterReceiver(myBroadcast4);
        unregisterReceiver(myBroadcast5);
        unregisterReceiver(myBroadcast6);
    }


   发送无序广播:  sendBroadcast方法
   //参数为广播的频道
        Intent intent=new Intent("mma");
        Bundle bundle=new Bundle();
        bundle.putString("mm","杨钰莹就是我的老婆!!!");  携带数据
        intent.putExtras(bundle);
        //发送广播(参数为意图对象)
        sendBroadcast(intent);

发送有序广播:  sendOrderedBroadcast方法
	//参数为广播的频道
        Intent intent2=new Intent("mma");
        Bundle bundle2=new Bundle();
        bundle2.putString("mm","杨钰莹就是我的小老婆!!!");
        intent2.putExtras(bundle2);
        //发送广播(参数为意图对象)
        sendOrderedBroadcast(intent2,null);

最后,再来一个本地广播对象,发送的广播只有本程序内部可以接收, LocalBroadcastManager对象

        localBroadcastManager=LocalBroadcastManager.getInstance(this);
<span style="white-space:pre">	</span><pre style="font-family: Consolas; font-size: 13.5pt; background-color: rgb(255, 255, 255);"><span style="background-color:#e4e4ff;"><span style="white-space:pre">	</span>localBroadcastManager</span>.sendBroadcast()  发送本地广播,参数也是意图对象





                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值