您的位置:首页 > 其它

广播接收者 BroadcastReceiver

2015-03-17 17:00 92 查看
广播接收者的作用:

简单来说,就是用于通讯.

同一进程间各大组件之间进行通讯.还可以用于不同进程间的通讯.

广播接受者的设计上,符合发布/订阅者模式.使发布者与接受者之间解耦,便于系统的集成与扩展.

广播接受者的生命周期只有OnRecive 方法. 而该方法是运行在主线程中的.如果在onReceive方法中执行大量的逻辑,耗时严重,会报anr错误.同时广播接受者生命周期比较的短,如果开启了子线程的话,启动的子线程随着广播接受者的消失而成为空进程,很容易被杀死.

所以,当广播接受到信息之后,如果要执行耗时的操作,可以开启一个服务来进行 或者 发送Notification.

用法:

实现一个类,继承自BroadcastReceiver,重写onReceive生命周期方法.

[code]
    public class OneReciver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Bundle bundle= intent.getExtras();

        if(bundle!=null){
            String name=(String) bundle.get("name");
            Log.v("tag", " One Reciver 姓名:"+name);
        }
    }

}


在功能清单文件中注册该自定义的广播接受者,并且设置过滤条件:

[code]<receiver android:name=".MyBroadcastReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>


以上是静态注册广播接受者的注册使用方式,在广播接受者而言,也可以通过代码的方式进行注册与释放.

[code]
    private NormalBroadCast oneCast;
    private NormalBroadCastTwo twoCast;
    private NormalBroadCastThree  threeCast;

     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        oneCast=new NormalBroadCast();
        twoCast=new NormalBroadCastTwo();
        threeCast=new NormalBroadCastThree();
    }

     //注册
     protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        IntentFilter filter=new IntentFilter();
        filter.addAction("xxx");

        this.registerReceiver(oneCast, filter);
        this.registerReceiver(twoCast, filter);
        this.registerReceiver(threeCast, filter);

    }

    //取消注册
     protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();

        this.unregisterReceiver(oneCast);
        this.unregisterReceiver(twoCast);
        this.unregisterReceiver(threeCast);
    }

   //发送广播

       public void send(View view){

        Intent intent=new Intent();
        intent.setAction("xxx");
        intent.putExtra("name","mingren");
        this.sendBroadcast(intent);
    }


两种注册方式分别被称为静态注册于动态注册.

对于静态注册的广播接受者而言,只要程序一旦运行,就会常驻内存中,所以,当我们启用另外的应用来发送广播的时候,只要广播接受匹配,就会被接收到.

对于动态注册的广播,只有Activity创建的时候,才会将广播注册到系统,当Activity销毁的时候,我们需要主动的取消注册.

广播的发送,存在三种形式:正常的发送,顺序的发送,停滞的发送

.例如上面的发送就属于正常的发送,当我们发送广播的时候,只要匹配,所有的广播接受者都会接受到该广播.

还有根据优先级发送广播,接受到广播的信息是有顺序的,高优先级的广播接受者有限接受到广播,然后才是低优先级的广播接受者接受广播.

[code]在xml文件中设定广播接受者的优先级:   (android:priority)


[code]
            <receiver android:name="com.example.normalbroadcastreciverdemo01.reciver.NormalBroadCastTwo">
           <intent-filter android:priority="700">
               <action android:name="android.intent.action.normal"></action>
           </intent-filter>
         </receiver>


优先级的数字越大,优先级越高.范围是在[-1000,1000]

然后在发送的时候调用:

[code]this.sendOrderedBroadcast(intent, null);


发送广播.

在广播传送的过程中,优先级高的会优先接受广播,而且,还有能力阻止广播向下传播.

[code]
        public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
                  String name=intent.getStringExtra("name");
                  Log.v("tag","Normal Three name:"+name);
                  //中断广播的发送
                  this.abortBroadcast();
    }


广播的发送方式还有所谓停滞广播.发送停滞广播,可以先发送广播,然后在注册该广播,接受发送到的消息.调用的方法:

[code]this.sendStickyBroadcast(intent);


介绍监听系统发送的广播来处理事务:

1 当网络变化时,处理事务:

[code]   <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
            </intent-filter>

    public void onReceive(Context context, Intent intent) {

        manager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        info=manager.getActiveNetworkInfo();
        if(info!=null&&info.isConnected()){
            int type=info.getType();
            if(ConnectivityManager.TYPE_MOBILE==type){
                Toast.makeText(context, "3g网络已连接",Toast.LENGTH_LONG).show();
            }else if(ConnectivityManager.TYPE_WIFI==type){
                Toast.makeText(context, "wifi已经连接", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(context, "网络无法识别",Toast.LENGTH_LONG).show();
            }
        }else{
            Toast.makeText(context, "网络没有连接", Toast.LENGTH_LONG).show();
        }

    }


此处添加权限:

[code]<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


2 获取发送过来短信的内容:

//将优先级调到最高

[code] <intent-filter android:priority="1000">
                <action android:name="android.provier.Telephony.SMS_RECEIVED">
                </action>
         </intent-filter>

//获取短信的内容

     Object[] objs=(Object[]) bundle.get("pdus");
            for(int i=0;i<objs.length;i++){
                byte[] buffer=(byte[]) objs[i];
                SmsMessage message=SmsMessage.createFromPdu(buffer);
                //获取短信的发送源
                String address=message.getOriginatingAddress();
                //获取短信的内容
                String body=message.getMessageBody();
                //获取短信的接受时间
                long time=message.getTimestampMillis();

                Date date=new Date(time);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy--MM--dd HH:mm:ss");
                //可识别的事件字符串
                String strDate=sdf.format(date);

                StringBuilder content=new StringBuilder();
                content.append("来源:"+address+" 内容:"+body+" 接受时间:"+strDate).toString();

                //按原地址给发送者回信
                SmsManager manager=SmsManager.getDefault();
                manager.sendTextMessage(address, null, "你妹啊!",null, null);

                //禁止向下传播
                this.abortBroadcast();

                Log.v("tag", content.toString());

注:


在广播接受者中启动其他的Activity时,需要加上:

[code] intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


然后在启动.

3 不允许拨打特定的号码:

[code]     <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL"></action>
            </intent-filter>

     public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if (action.equals(intent)) {
            String data = this.getResultData();
            System.out.println("================");
            if ("5556".equals(data)) {
            //将数据置空
                this.setResultData(null);
            }
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: