简体   繁体   中英

broadcast receiver onReceive not working in the fragment

I send broadcastreceiver from activity to fragment. my problem is the onReceive not working.

 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);

Any help please. Thanks in advance

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

I've managed it before. Here is the code (it is a bit different than yours, cause mine never displayed - just ran in the background. Hopefully it helps a bit)

public class BroadcastReceiverTask extends Fragment {

/**
 * Callback interface through which the fragment will report the
 * task's progress and results back to the Activity. Calling activity MUST implement this.
 */
public interface BroadcastCallbacks {
    void onBroadcastReceived(boolean error, String message);
    void onProgressReceived(String message);
}

/** The calling activity. */
private BroadcastCallbacks mCallbacks;

/** Create a new instance. */
public static BroadcastReceiverTask newInstance() {
    BroadcastReceiverTask f = new BroadcastReceiverTask();

    // Supply index input as an argument.
    Bundle args = new Bundle();
    f.setArguments(args);

    return f;
}

/**
 * Hold a reference to the parent Activity so we can report the
 * task's current progress and results. The Android framework
 * will pass us a reference to the newly created Activity after
 * each configuration change.
 */
@Override
public void onAttach(Context activity) {
    super.onAttach(activity);
    if (activity instanceof BroadcastCallbacks) {
        mCallbacks = (BroadcastCallbacks) activity;
    } else {
        Log.w("BroadcastTask", "CALLING CLASS DOES NOT IMPLEMENT INTERFACE!");
    }
}


/**
 * This method will only be called once when the retained
 * Fragment is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra(SubmitInspectionService.BROADCAST_MESSAGE);
            if (intent.hasExtra(SubmitInspectionService.BROADCAST_IS_PROGRESS)) {
               receivedProgress(message);
            } else if (intent.hasExtra(SubmitInspectionService.BROADCAST_IS_ERROR)) {
                boolean isError = intent.getBooleanExtra(SubmitInspectionService.BROADCAST_IS_ERROR, false);
                receivedEndMessage(isError, message);
            }
        }
    };

    IntentFilter filter = new IntentFilter(SubmitInspectionService.BROADCAST_ACTION);
    LocalBroadcastManager.getInstance(getContext()).registerReceiver(mBroadcastReceiver, filter);
}

/** Call to the activity to give an update on the progress.
 *
 * @param message The message to display.
 */
private void receivedProgress(String message) {
    if (isAdded() && mCallbacks != null) {
        mCallbacks.onProgressReceived(message);
    }
}

/** Call to the activity to signal submit END as well as the error state.
 *
 * @param isError TRUE if an error occurred.
 * @param message The message to display.
 */
private void receivedEndMessage(boolean isError, String message) {
    if (isAdded() && mCallbacks != null) {
        mCallbacks.onBroadcastReceived(isError, message);
    }
}

/**
 * Set the callback to null so we don't accidentally leak the
 * Activity instance.
 */
@Override
public void onDetach() {
    super.onDetach();
    mCallbacks = null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM