广播是用来不同的组件之间通信的,一个组件发送广播,另外一个组件接受广播,然后做需要的处理。比方说在Q Activity中点击某个按钮,想要关闭E Activity时,那么在Q发送一个广播,并且指定Action(可以认为是标签),在E定一个广播接受者,E接收到了Q发来的广播,就可以在里面做相应的处理。
Q Activity中发送广播:
Intent intent=new Intent();
intent.setAction("com.zhangli.finishActivity");
sendBroadcast(intent);
E Activity中的广播接受者,其中给广播进行了动态注册:
public class EActivity extends Activity{
private MyBroadcastReceiver myBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_list_layout);
//给广播注册(从QActivity得到关闭的广播)
myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.zhangli.finishActivity");
registerReceiver(myBroadcastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//关闭广播,节约内存
unregisterReceiver(myBroadcastReceiver);
myBroadcastReceiver=null;
}
静态注册(配置清单中),定义广播接受的优先级:-1000~1000
<receiver android:name=".utils.CircleMenuLayout$MyBroadcastReceiver">
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.MYXUANZHUAN" />
</intent-filter>
</receiver>
终止广播:
abortBroadcast();
在onDestory()中销毁:
unregisterReceiver(myGengxinReceiver);
myGengxinReceiver=null;
不管广播是否被其他接收者终止,最后FinalReceiver 都会接收到。
sendOrderedBroadcast(intent, null,new FinalReceiver(), null, 0, null, null);
广播注册,可以写在Activity(onCreate),也可以写在Fragment(onActivityCreated)里。
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getActivity()); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.CART_BROADCAST");//建议把它写一个公共的变量,这里方便阅读就不写了。 BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent){ System.out.println("OK"); } }; broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
发送广播
Intent intent = new Intent("android.intent.action.CART_BROADCAST"); LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
在Activity中接收到从Fragment发来的广播,要多添加一个manager:
mBroadcastManager = LocalBroadcastManager.getInstance(this);
myBroadcastReceiver = new ClearBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constants.ADRESSFRAGMENT_BRODCAST);
mBroadcastManager.registerReceiver(myBroadcastReceiver, intentFilter);