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)

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

相关推荐
2501_9151063220 小时前
iOS 26 APP 性能测试实战攻略:多工具组合辅助方案
android·macos·ios·小程序·uni-app·cocoa·iphone
怪兽20141 天前
IntentService 的应用场景和使用方式?
android·面试
Jeled1 天前
云信im在Android中的使用2
android
Jerry1 天前
Compose 自定义布局和图形
android
杨筱毅1 天前
【Android】【底层机制】组件生命周期以及背后的状态管理
android·底层机制
Jeled1 天前
Kotlin 实现社交 App 音视频模块:语音录制、播放、暂停与进度控制全流程封装
android·kotlin·android studio·音视频
沐怡旸1 天前
【底层机制】【Android】Binder架构与原理
android·面试
Jeled1 天前
Jetpack —> Media3的分析和使用
android
木易士心1 天前
Android setContentView源码与原理分析
android
00后程序员张1 天前
iOS混淆与IPA文件加固全流程实战 防止苹果应用被反编译的工程级方案
android·ios·小程序·https·uni-app·iphone·webview