Search code examples
androidandroid-fragmentsbroadcastreceiverandroid-broadcastreceiver

Android Fragment - BroadcastReceiver call fragment method


I have a BroadcastReceiver which receives broadcast sent to a Fragment. I'm getting the broadcast but how can I call a method from the Fragment itself? I basically need to update a List once the broadcast arrives, the List & update method are part of the Fragment.

public class FragmentReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action != null && action.equals("AllTasksFragmentUpdate"))
        {
            //
        }
    }
}

Registering the receiver:

    @Override
public void onCreate(final Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getActivity().registerReceiver(new FragmentReceiver(), new IntentFilter("AllTasksFragmentUpdate"));
}

How can I call the method from the Fragment?


Solution

  • You can implement your broadcast reciever in the following way:

    import android.app.Fragment;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.content.LocalBroadcastManager;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.adobe.libs.connectors.R;
    
    public class YourFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater,
                                    @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            super.onCreateView(inflater, container, savedInstanceState);
            //Start listening for refresh local file list   LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mYourBroadcastReceiver,
                    new IntentFilter(<YOUR INTENT FILTER>));
    
            return inflater.inflate(R.layout.your_fragment_layout, null, true);
        }
    
        @Override
        public void onDestroyView() {
            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mYourBroadcastReceiver);
        }
    
        private final BroadcastReceiver mYourBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // Now you can call all your fragments method here
            }
        };
    }