【Android】广播的写法

  • 发送广播

/***小喇叭发出数据已经跟新的广播*/privatevoidbroadcastCircleViewUpdate(){//创建IntentIntenttestIntent=newIntent();//设置动作属性testIntent.setAction(Action.ACTION_CIRCLE_MSG_UPDATE);//设置消息内容testIntent.putExtra("MSG","Test!!!!");//发送广播getBaseContext().sendBroadcast(testIntent);}

  • 接受广播

【1】先写一个广播监听对象: receiver

privateBroadcastReceiverreceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentintent){//讲广播中收到的intent的属性取出来Stringaction=intent.getAction();//使用if-elseif进行哦匹配;注意不要使用switchif(action.equals(BroadCastAction.NEW_POST_ACTION)){//添加需要执行的动作......}elseif(action.equals(BroadCastAction.NEW_POST_SUCCESS_ACTION)){//添加需要执行的动作......}elseif(action.equals(BroadCastAction.NEW_POST_FAIL_ACTION)){//添加需要执行的动作......}elseif(action.equals(Action.ACTION_CIRCLE_MSG_UPDATE)){//添加需要执行的动作Stringmsg=intent.getStringExtra("MSG");......}elseif(action.equals(Action.ACTION_CIRCLE_HOME_UPDATE)){//添加需要执行的动作......}elseif(action.equals(Action.ACTION_CIRCLE_PERSONAL_UPDATE)){//添加需要执行的动作......}}};


【2】集中注册所有的监听

/***集中注册监听*/privatevoidregistRecivers(){IntentFilterfilter=newIntentFilter();filter.addAction(BroadCastAction.NEW_POST_ACTION);filter.addAction(BroadCastAction.NEW_POST_SUCCESS_ACTION);filter.addAction(BroadCastAction.NEW_POST_FAIL_ACTION);filter.addAction(Action.ACTION_CIRCLE_MSG_UPDATE);filter.addAction(Action.ACTION_CIRCLE_HOME_UPDATE);filter.addAction(Action.ACTION_CIRCLE_PERSONAL_UPDATE);//注册走起:参数1为receiver,参数2为intent过滤器registerReceiver(receiver,filter);}


【3】广播的注册与卸载

protectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_firend_circle);......//在Activity中onCreate()中集中注册registRecivers();}@OverrideprotectedvoidonDestroy(){super.onDestroy();//注意一定要卸载,不然运行会报错unregisterReceiver(receiver);}


好东西总是在最后!!!

BroadcastReciver需要能匹配的intent,共有2种方式

【1】使用代码进行制定,如下

privatevoidregistRecivers(){IntentFilterfilter=newIntentFilter();filter.addAction(BroadCastAction.NEW_POST_ACTION);filter.addAction(BroadCastAction.NEW_POST_SUCCESS_ACTION);filter.addAction(BroadCastAction.NEW_POST_FAIL_ACTION);filter.addAction(Action.ACTION_CIRCLE_MSG_UPDATE);filter.addAction(Action.ACTION_CIRCLE_HOME_UPDATE);filter.addAction(Action.ACTION_CIRCLE_PERSONAL_UPDATE);//注册走起:参数1为receiver,参数2为intent过滤器registerReceiver(receiver,filter);}

【2】在AndroidManifest.xml文件中进行配置

<receiverandroid:name="com.zte.moa.receiver.SipBroadcastReceiver"><intent-filter><actionandroid:name="com.zte.moa.call_action.org.doubango.ngn.services.impl.NgnHttpClientService"/></intent-filter></receiver>

这里有个坑!!!用sipBroadcastReceiver.java来举个例子

使用方式【2】的话是有条件的:sipBroadcastReceiver.java 必须存在这个类

一定一定!!!!不能在Activity中写成内部类sipBroadcastReceiver,这样会报错!!!

网上看到已经有哥么掉坑里去过了:

http://www.verydemo.com/demo_c131_i26767.html