android 四大组件—BroadcastReceiver

无序广播(普通广播) 和 有序广播(Ordered Broadcast)

1. 无序广播(普通广播)

Intent intent = new Intent("com.example.MY_BROADCAST");

sendBroadcast(intent);

2. 有序广播

Intent intent = new Intent("com.example.MY_ORDERED_BROADCAST");

sendOrderedBroadcast(intent, null); // 第二个参数是权限

系统会根据接收者的 priority 从高到低依次调用 onReceive()

中断广播:abortBroadcast();

修改结果:setResultExtras(Bundle);

获取前一个接收者的结果:getResultExtras(true)。

静态注册(Manifest 中声明)

复制代码
<receiver
    android:name=".BootReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
            // 开机完成
        }
    }}

动态注册(代码中注册)

val receiver = object : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {

// 处理广播

}}

// 注册registerReceiver(receiver, IntentFilter("MY_ACTION"))

// 解绑(必须)unregisterReceiver(receiver)

功能:接收并响应广播(系统或应用发出)。

相关推荐
JMchen1233 小时前
现代Android图像处理管道:从CameraX到OpenGL的60fps实时滤镜架构
android·图像处理·架构·kotlin·android studio·opengl·camerax
快点好好学习吧4 小时前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
是誰萆微了承諾4 小时前
php 对接deepseek
android·开发语言·php
Dxy12393102165 小时前
MySQL如何加唯一索引
android·数据库·mysql
冠希陈、7 小时前
PHP 判断是否是移动端,更新鸿蒙系统
android·开发语言·php
晚霞的不甘9 小时前
Flutter for OpenHarmony从零到一:构建《冰火人》双人合作闯关游戏
android·flutter·游戏·前端框架·全文检索·交互
2601_949833399 小时前
flutter_for_openharmony口腔护理app实战+饮食记录实现
android·javascript·flutter
独自破碎E9 小时前
【滑动窗口+字符计数数组】LCR_014_字符串的排列
android·java·开发语言
stevenzqzq9 小时前
compose 中 align和Arrangement的区别
android·compose
VincentWei9510 小时前
Compose:MutableState 和 mutableStateOf
android