首页 > 解决方案 > 广播接收器 onReceive 在片段中不起作用

问题描述

我将广播接收器从活动发送到片段。我的问题是 onReceive 不起作用。

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
      container, Bundle savedInstanceState) {

    IntentFilter(Constants.BroadCastMessages.UI_NEW_CHAT_ITEM));

    onNotice = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){

                case Constants.BroadCastMessages.UI_NEW_CHAT_ITEM:

                    Log.d("RokayahBroadcast" , "from on receive");
            }

        }
    };

  public void onResume() {
    super.onResume();

    IntentFilter iff = new 
       IntentFilter(Constants.BroadCastMessages.UI_NEW_CHAT_ITEM);
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(onNotice , iff);

   @Override
public void onPause() {
    super.onPause();
    getActivity().unregisterReceiver(onNotice);

请提供任何帮助。提前致谢

标签: javaandroid

解决方案


据我所知,BroadcastReceiver 不能注册到 Fragment 中,而是注册到 Activity 中:您可能应该在 Activity 级别注册此接收器,然后一旦收到将其传递给您的 Fragment。


推荐阅读