Android——静态注册广播

静态注册广播

通过右键新建一个广播

此时,AndroidManifest.xml文件中会有以下代码

xml 复制代码
        <receiver
            android:name=".receiver.ShockReceiver"
            android:enabled="true"
            android:exported="true">

        </receiver>

enabled:是否启用该广播,默认为true,可以不写

exported:是否可跨应用使用该广播,如果为false,则只能在当前应用中接收广播

添加意图过滤器

xml 复制代码
        <receiver
            android:name=".receiver.ShockReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.study_android.shock"/>
            </intent-filter>
        </receiver>

定义广播接收者

java 复制代码
public class ShockReceiver extends BroadcastReceiver {
    public static final String SHOCK_ACTION = "com.example.study_android.shock";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getAction().equals(SHOCK_ACTION)) {
            // 从系统服务中获取震动管理器
            Vibrator vb = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            // 命令震动器震动若干秒,单位:毫秒
            vb.vibrate(500);
        }
    }
}

发送广播

java 复制代码
    @Override
    public void onClick(View view) {
        // Android8.0之后删除了大部分静态注册,防止退出App后仍在接收广播,
        // 为了让应用能够继续接收静态广播,需要给静态注册的广播指定包名。

        String fullName = "com.example.study_android.receiver.ShockReceiver";
        Intent intent = new Intent(ShockReceiver.SHOCK_ACTION);
        // 发送静态广播时,需要通过setComponent方法指定接收器的完整路径
        ComponentName componentName = new ComponentName(this, fullName);
        // 设置意图的组件信息
        intent.setComponent(componentName);
        sendBroadcast(intent);
    }

案例代码

相关推荐
独行soc10 小时前
2026年渗透测试面试题总结-20(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮
常利兵10 小时前
2026年,Android开发已死?不,它正迎来黄金时代!
android
Risehuxyc10 小时前
备份三个PHP程序
android·开发语言·php
Doro再努力20 小时前
【Linux操作系统10】Makefile深度解析:从依赖推导到有效编译
android·linux·运维·服务器·编辑器·vim
Daniel李华20 小时前
echarts使用案例
android·javascript·echarts
做人不要太理性21 小时前
CANN Runtime 运行时组件深度解析:任务调度机制、存储管理策略与维测体系构建逻辑
android·运维·魔珐星云
我命由我1234521 小时前
Android 广播 - 静态注册与动态注册对广播接收器实例创建的影响
android·java·开发语言·java-ee·android studio·android-studio·android runtime
朗迹 - 张伟1 天前
Tauri2 导出 Android 详细教程
android
lpruoyu1 天前
【Android第一行代码学习笔记】Android架构_四大组件_权限_持久化_通知_异步_服务
android·笔记·学习
独自破碎E1 天前
【BISHI15】小红的夹吃棋
android·java·开发语言