How to registerReceiver in Fragment?

androidq
androidq
2 Points
1 Posts

I want to update recycler view through Alarm Manager at a sepcific interval. To this I'm using BroadcastReceiver to receive the task completion:

public class MyFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private MyInterface mListener;
     private View view1;
    RecyclerView recyclerView;


    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            /*Bundle bundle = intent.getExtras();
            if (bundle != null) {
                String string = bundle.getString("");
                int resultCode = bundle.getInt("");

            }*/
            
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
         registerReceiver(receiver, new IntentFilter(
                DummyContent.CHATRECIEVEDNOTIFICATION));
    }
    @Override
    public void onPause() {
        super.onPause();
         unregisterReceiver(receiver);
    }

But getting error on registerReceiver and unregisterReceiver:

Views: 136
Total Answered: 1
Total Marked As Answer: 1
Posted On: 15-Feb-2020 02:11

Share:   fb twitter linkedin
All these variables and methods are blongs with activity. So use getActivity() to call these.
 - Stevan  15-Feb-2020 02:25
Answers
Rashmi
Rashmi
Member
130 Points
30 Posts
         

Yes, These variables and methods belongs to activity class. So we need to get parent active context to use these in fragment class:

    @Override
    public void onResume() {
        super.onResume();
        getActivity().registerReceiver(receiver, new IntentFilter(
                DummyContent.CHATRECIEVEDNOTIFICATION));
    }
    @Override
    public void onPause() {
        super.onPause();
        getActivity().unregisterReceiver(receiver);
    }
Posted On: 15-Feb-2020 02:28
Thanks for quick response.
 - androidq  15-Feb-2020 02:31
 Log In to Chat