1、发送广播的代码
//1、fragment中的使用
Intent redIntent=new Intent("com.asia5b.red.my.a5b");
getActivity().sendBroadcast(redIntent); //发送小红点广播
//2、activity中的使用
Intent redIntent=new Intent("com.asia5b.red.shoppong.card");
sendBroadcast(redIntent); //发送小红点广播
2、注册广播的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//小红点显示
//创建这个方法,开启广播监听
registerRedBroadrecevicer();
}
//小红点广播
public RedBoradCastReceiver redReceiver;
public void registerRedBroadrecevicer() {
//获取广播对象
redReceiver = new RedBoradCastReceiver(this);
//创建意图过滤器
IntentFilter redFilter = new IntentFilter();
//添加动作
redFilter.addAction("com.asia5b.red.shoppong.card");
redFilter.addAction("com.asia5b.red.my.a5b");
registerReceiver(redReceiver, redFilter);
}
3、反注册 销毁广播的代码
@Override
protected void onDestroy() {
unregisterReceiver(redReceiver);
super.onDestroy();
}
4、重写广播接收器,做自己的逻辑操作
public class RedBoradCastReceiver extends BroadcastReceiver {
private MainActivity mainActivity;
public RedBoradCastReceiver(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
@Override
public void onReceive(Context context, final Intent intent) {
Log.e("bbbbb","aaaaaaaaaaaaaa");
mainActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if ("com.asia5b.red.shoppong.card".equals(intent.getAction())){
mainActivity.shopping_card_red_iv.setVisibility(View.VISIBLE);
}else if ("com.asia5b.red.my.a5b".equals(intent.getAction())){
mainActivity.my_a5b_red_iv.setVisibility(View.VISIBLE);
}
}
});
}
}