Android BroadcastReceiver在Fragment中的使用

BroadcastReceiver在activity中调用很简单,但是换成Fragment后
在Activity中操作BroadcastReceiver的方法在Fragment就不管用了
现项目需要在Fragment中设置BroadcastReceiver
然后发现不能注册广播了
查了一下资料,只要改动一下就能生效了
  • 首先在Fragment中还是先建立BroadcastReceiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //这里写需要的业务逻辑
        }
    };
  • 然后onCreateView()中创建
@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);
    }
    原文作者:lzokks04
    原文地址: https://blog.csdn.net/lzokks04/article/details/52531852
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞