广播接收器onReceive在片段中不起作用

时间:2018-12-19 09:00:11

标签: java android

从活动向片段发送broadcastreceiver。我的问题是onReceive无法正常工作。

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

请任何帮助。 预先感谢

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我以前已经处理过。这是代码(与您的代码有些不同,因为我的代码从未显示-只是在后台运行。希望可以有所帮助)

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