通過自定義廣播接收器傳達兩個活動
你可以傳達兩個活動,以便可以向活動 A 通知活動 B 中發生的事件。
活動 A.
final String eventName = "your.package.goes.here.EVENT";
@Override
protected void onCreate(Bundle savedInstanceState) {
registerEventReceiver();
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
unregisterEventReceiver(eventReceiver);
super.onDestroy();
}
private void registerEventReceiver() {
IntentFilter eventFilter = new IntentFilter();
eventFilter.addAction(eventName);
registerReceiver(eventReceiver, eventFilter);
}
private BroadcastReceiver eventReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//This code will be executed when the broadcast in activity B is launched
}
};
活動 B.
final String eventName = "your.package.goes.here.EVENT";
private void launchEvent() {
Intent eventIntent = new Intent(eventName);
this.sendBroadcast(eventIntent);
}
當然,你可以向廣播新增更多資訊,為活動之間傳遞的 Intent 新增額外內容。未新增以保持示例儘可能簡單。