BroadcastReceiver在activity中调用很简单,但是换成Fragment后
在Activity中操作BroadcastReceiver的方法在Fragment就不管用了
现项目需要在Fragment中设置BroadcastReceiver
然后发现不能注册广播了
查了一下资料,只要改动一下就能生效了
- 首先在Fragment中还是先建立BroadcastReceiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//这里写需要的业务逻辑
}
};
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_battery, container, false);
unBinder = ButterKnife.bind(this, view);
//在此处加入意图以及注册BroadcastReceiver
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
getActivity().getApplicationContext().registerReceiver(receiver, filter);
return view;
}
- 最后别忘了把广播反注册了,在onDestroy()中
@Override
public void onDestroy() {
super.onDestroy();
getActivity().getApplicationContext().unregisterReceiver(receiver);
}