Sending and receiving broadcast messages enables inter activity communication. Suppose in activity A you have completed a task and you want activity B to react accordingly, then broadcasting helps a lot. A only needs to initialize an intent and send it via a broadcast message. B needs to set a filter to get the specific messages from A and register a receiver, where the actions upon receving messages are defined.
In activity A, the message can be sent this way
Intent broadcastI=new Intent();
broadcastI.setAction("edu.hkust.cse.phoneAdapter.ruleChange");
sendBroadcast(broadcastI); In activity B, the filter and receiver
IntentFilter filter=new IntentFilter("edu.hkust.cse.phoneAdapter.ruleChange");
this.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(getApplicationContext(), "msg received", Toast.LENGTH_SHORT).show();
}
},filter);
Easy, right?
本文详细介绍了在Android开发中使用广播消息实现组件间通信的方法。通过实例演示了如何在Activity A完成任务后,向Activity B发送广播消息,以及Activity B如何接收到并响应这些消息。此过程简化了跨组件的交互逻辑。

5417

被折叠的 条评论
为什么被折叠?



