在Android中,Broadcast是一種跨進(jìn)程通信(IPC)的方式。它允許應(yīng)用程序發(fā)送和接收消息,而無需直接相互調(diào)用。以下是實(shí)現(xiàn)跨進(jìn)程通信的步驟:
Intent
對(duì)象創(chuàng)建要發(fā)送的消息。sendBroadcast()
方法將Intent
發(fā)送到廣播總線。示例代碼:
Intent intent = new Intent("com.example.MY_BROADCAST");
intent.putExtra("key", "value");
sendBroadcast(intent);
BroadcastReceiver
的類,并重寫onReceive()
方法。AndroidManifest.xml
文件中聲明廣播接收器,或使用registerReceiver()
方法在運(yùn)行時(shí)動(dòng)態(tài)注冊(cè)。示例代碼:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ("com.example.MY_BROADCAST".equals(action)) {
String data = intent.getStringExtra("key");
// 處理接收到的消息
}
}
}
在AndroidManifest.xml
中聲明:
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.MY_BROADCAST" />
</intent-filter>
</receiver>
或使用registerReceiver()
方法:
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter("com.example.MY_BROADCAST");
registerReceiver(myBroadcastReceiver, intentFilter);
onReceive()
方法中處理接收到的廣播消息。注意:
ContentProvider
、Socket
或Messenger
。LocalBroadcastManager
可以在同一應(yīng)用程序的不同組件之間發(fā)送和接收廣播,而無需通過網(wǎng)絡(luò)。這對(duì)于不需要跨網(wǎng)絡(luò)通信的場(chǎng)景非常有用。