How to registerReceiver in Fragment

The registerReceiver() and unregisterReceiver() methods are methods of the Context class. In this case, you need your Activity (which is a Context).

Fragments provide easy access to their containing Activity via the getActivity() method.

RESULT_CANCELED is simply a static variable on the Activity class, so you can access it anywhere via Activity.RESULT_CANCELED.


All these methods and variables belong to Activity class. So consider calling them with context of parent Activity of Fragment.

You may call required methods as:

 requireActivity().registerReceiver(receiver, filter);

and

 requireActivity().unregisterReceiver(receiver);

if(resultCode==RESULT_CANCELED){

can be replaced with

if(resultCode == Activity.RESULT_CANCELED){

Hope this solve your problem.


Regarding to a broadcast message, you won't receive anything if you register like that:

getActivity().registerReceiver(receiver, filter);

You should write either:

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);

For instance, case of an intent sent from a service (IntentService).