android

Android Broadcast怎样实现跨进程通信

小樊
95
2024-10-12 22:06:25
栏目: 编程语言

在Android中,Broadcast是一种跨进程通信(IPC)的方式。它允许应用程序发送和接收消息,而无需直接相互调用。以下是实现跨进程通信的步骤:

  1. 发送广播

示例代码:

Intent intent = new Intent("com.example.MY_BROADCAST");
intent.putExtra("key", "value");
sendBroadcast(intent);
  1. 注册广播接收器

示例代码:

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);
  1. 处理广播

注意:

0
看了该问题的人还看了