android写一个发送广播和接收广播Activity之间传递的全部代码
时间: 2024-03-25 13:37:45 浏览: 25
下面是一个简单的 Activity 之间传递数据的完整代码示例:
发送广播的 Activity:
```java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 发送自定义广播
Intent intent = new Intent("com.example.MY_CUSTOM_ACTION");
intent.putExtra("message", "Hello world!");
sendBroadcast(intent);
}
}
```
接收广播的 Activity:
```java
public class SecondActivity extends AppCompatActivity {
private BroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// 动态注册广播接收器
receiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.MY_CUSTOM_ACTION");
registerReceiver(receiver, filter);
}
@Override
protected void onDestroy() {
// 取消注册广播接收器
unregisterReceiver(receiver);
super.onDestroy();
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.example.MY_CUSTOM_ACTION")) {
// 获取广播中的消息
String message = intent.getStringExtra("message");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
}
```
在 AndroidManifest.xml 文件中注册 SecondActivity:
```xml
<activity android:name=".SecondActivity"/>
```
注意:在接收广播的 Activity 中,需要使用动态注册方式注册广播接收器,并在 Activity 销毁时取消注册。此外,需要在 AndroidManifest.xml 文件中注册接收广播的 Activity。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)