用安卓写出 发送广播和接收广播
时间: 2023-09-29 11:08:28 浏览: 85
发送广播:
```
Intent intent = new Intent();
intent.setAction("com.example.MY_BROADCAST");
intent.putExtra("message", "Hello World!");
sendBroadcast(intent);
```
接收广播:
在AndroidManifest.xml文件中注册接收者:
```
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.MY_BROADCAST" />
</intent-filter>
</receiver>
```
创建BroadcastReceiver类:
```
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
```
注意:需要在AndroidManifest.xml文件中申请接收广播的权限:
```
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
```
阅读全文