我必須將Broadcast從BroadcastAcerer傳遞給MainActivity。然後,我會將這個字符串放在碎片中,我該如何做到這一點?將字符串從BroadcastReceiver傳遞給MainActivity,並將其獲取到片段中
MyReceiver.java
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Bus bus = new Bus();
bus.post(new InformationEvent("your string"));
}
}
ScarsdaleHome.java(片段)
@Subscribe public void answerAvailable(InformationEvent event) {
String yourString= event.getInf();
Toast.makeText(getActivity(), yourString, Toast.LENGTH_LONG).show();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.scarsdale_home_activity, container, false);
bus = new Bus();
bus.register(this);
return rootView;
}
InformationEvent.java
public class InformationEvent {
private String inf;
public InformationEvent(String inf) {
this.inf = inf;
}
public String getInf() {
return inf;
}
}
我嘗試了一切,但沒有任何工作:(
好吧,我用你的代碼,我把吐司在answerAvailable但是當廣播接收器被稱爲I無法看到Toast通知.. – Slaiv206 2015-03-25 11:29:50
@ Slaiv206確保您在'Activity'和'BroadcastReceiver'中使用相同的Bus實例。 – 2015-03-25 12:13:56
@EgorN:我發佈了代碼,我不明白你的意思,請你解釋一下更好嗎? – Slaiv206 2015-03-25 12:26:16