这就是我正在做的事情:
我正在使用MainActvity
从Fragment
向LocalBroadcastManager
发送意图。我在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);
}
}
为什么那个接收器没有被调用?有什么帮助吗?
答案 0 :(得分:1)
您正在使用this.sendBroadcast(i)
发送全球,应用内广播,LocalBroadcastManager
无法接收。
在MainActivity
中,替换
this.sendBroadcast(i);
与
LocalBroadcastManager.getInstance(this).sendBroadcast(i);
这样可行。
答案 1 :(得分:0)
我的问题解决了从onPause()移除接收器unregister()。