1、首先new一个广播:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Constant.RECEIVER)) { } } };
2、定义一个全局布尔类型的变量:
private boolean mAttached;
3、重写onAttachedToWindow()方法,在里面注册广播
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (!mAttached) { mAttached = true; IntentFilter filter = new IntentFilter(); filter.addAction(Constant.CHANGE_SKIN_RECEIVER); getContext().registerReceiver(mReceiver, filter); } }
4、重写onDetachedFromWindow(),在里面注销广播
@Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mAttached){ mAttached = false; getContext().unregisterReceiver(mReceiver); } }