通过自定义广播接收器传达两个活动
你可以传达两个活动,以便可以向活动 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 添加额外内容。未添加以保持示例尽可能简单。