没有调用LocalBroadcastManager onReceive()

时间:2015-03-24 12:35:38

标签: android android-intent broadcastreceiver android-broadcast localbroadcastmanager

这就是我正在做的事情:

我正在使用MainActvityFragmentLocalBroadcastManager发送意图。我在Fragment类的onReceive()中编写了onCreateView()代码。我在onDestroy()中取消注册接收者。

但是onReceive()没有被调用。为什么呢?

MainActivity 类中:

   void handleText()
{ 
          Intent i = new Intent("receiveURL");
          i.putExtra("key", sharedText);

          this.sendBroadcast(i);
}

在我的片段类中:

public class AddTab extends Fragment implements View.OnClickListener {

    BroadcastReceiver  receiver;

    EditText textBox;

        @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_add, container, false);

        textBox = (EditText) view.findViewById(R.id.editText);

        receiver = new BroadcastReceiver() {
//This is not getting called
            @Override
            public void onReceive(Context context, Intent intent) {
                String g = intent.getStringExtra("key");
                textBox = (EditText) getView().findViewById(R.id.editText);
                if (textBox != null){
                    textBox.setText(g);}
                else{
                    Log.d("NULL", "");
                }

                Log.d("received","");
                }
            };

      LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("receiveURL"));
...
//some code
    }


    public void onDestroy() {


         super.onDestroy();
         LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
    }

}

为什么那个接收器没有被调用?有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

您正在使用this.sendBroadcast(i)发送全球,应用内广播,LocalBroadcastManager无法接收。

MainActivity中,替换

this.sendBroadcast(i);

LocalBroadcastManager.getInstance(this).sendBroadcast(i);

这样可行。

答案 1 :(得分:0)

我的问题解决了从onPause()移除接收器unregister()。