这就是我要做的:
我正在使用MainActvity将一个意图从Fragment发送到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);
}
}为什么那个接收器不接电话?有什么帮助吗?
发布于 2015-03-24 12:41:40
您使用的是this.sendBroadcast(i),它发送一个LocalBroadcastManager不会接收到的全局应用程序间广播。
在MainActivity中,替换
this.sendBroadcast(i);使用
LocalBroadcastManager.getInstance(this).sendBroadcast(i);这会管用的。
发布于 2017-08-16 08:43:39
我的问题是从onPause()中删除接收方取消寄存器()。
https://stackoverflow.com/questions/29232807
复制相似问题