写一个,跨进程使用BroadcastReciver的例子
时间: 2024-04-30 20:22:49 浏览: 41
假设我们要实现一个跨进程的计算器应用,当用户在应用中输入两个数字和操作符后,计算结果需要显示在另一个进程中的UI界面上。我们可以使用BroadcastReceiver来实现这个功能。
首先,在发送广播的进程中,我们需要创建一个BroadcastReceiver来接收计算结果,并将结果发送到另一个进程中。代码如下:
```
public class CalculatorResultReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
double result = intent.getDoubleExtra("result", 0.0);
Intent broadcastIntent = new Intent("com.example.calculator.CALCULATOR_RESULT");
broadcastIntent.putExtra("result", result);
context.sendBroadcast(broadcastIntent);
}
}
```
在这个Receiver中,我们从Intent中获取计算结果,并将结果封装到一个新的Intent中,然后发送给另一个进程。
接下来,在接收广播的进程中,我们需要创建一个BroadcastReceiver来接收计算结果并更新UI界面。代码如下:
```
public class CalculatorResultReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
double result = intent.getDoubleExtra("result", 0.0);
TextView resultTextView = (TextView) findViewById(R.id.result_text_view);
resultTextView.setText(String.valueOf(result));
}
}
```
在这个Receiver中,我们从Intent中获取计算结果,并使用findViewById方法获取UI界面中的TextView控件,然后更新UI界面上的结果。
最后,在发送广播的地方,我们需要创建一个Intent,并将计算结果封装到Intent中,然后发送广播。代码如下:
```
Intent intent = new Intent("com.example.calculator.CALCULATOR_RESULT");
intent.putExtra("result", result);
sendBroadcast(intent);
```
在这个Intent中,我们指定了广播的Action为"com.example.calculator.CALCULATOR_RESULT",这个Action需要和接收广播的地方注册的Action相同。然后我们将计算结果封装到Intent中,并发送广播。
这样,我们就完成了一个跨进程使用BroadcastReceiver的例子。当用户在应用中进行计算后,计算结果会自动显示在另一个进程的UI界面上。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)