Search code examples
androidandroid-intentbroadcastreceiverintentfilter

Custom BroadcastReceiver won't receive the broadcast


I have 5 fragments on a ViewPager (they're all in memory all the time, onPause() and such are never called while the containing Activity is on screen).

Anyway, I need to update one fragment (GroupsListFragment) depending on what's happening in another one (TimetableListFragment). I'm using LocalBroadcastManager and a BroadcastReceiver for this.

Now on to the relevant parts. Registering for the broadcast Intent (severely abbreviated):

public class GroupsListFragment extends Fragment {
        @Override
        public void onResume() {
            super.onResume();
            mBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
            mBroadCastReceiver = new UpdateGroupsReceiver(this);
            IntentFilter iFilter = new IntentFilter(UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION);
            Log.d("GroupsListFragment", "Registering for receiver with intentfilter:[action=" + iFilter.getAction(0) + "]");
            mBroadcastManager.registerReceiver(mBroadCastReceiver, iFilter);
        }
}

Sending the broadcast (once again severely abbreviated):

public class TimetableListFragment extends Fragment {
    public void updateStatus() {
        Intent intent = new Intent(UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION);
        mBroadcastManager.sendBroadcast(intent);
        Log.d(TAG, "Sending broadcast with intent:[action=" + intent.getAction() + "]");
    }
}

The problem is that my UpdateGroupsReceiver never receives it (onReceive() is never fired).

Any advice on what might be the culprit?


Solution

  • I am using this code that is working well

    @Override
    public void onResume() {
        super.onResume();
        if (myReceiver == null) {
            myReceiver = new UpdateGroupsReceiver(this);
            IntentFilter filter = new IntentFilter(
                  UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION);
            registerReceiver(myReceiver, filter);
        }
    }
    
    public void updateStatus() {
        Intent intent = new Intent();
        intent.setAction(UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION);
        sendBroadcast(intent);
    }
    

    A runnig minimal example testapp can be found at https://github.com/k3b/EzTimeTracker/ under BroadCastTest.