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);
    }

案例代码

相关推荐
厮年断弦4 小时前
AI 辅助开发实录:一周做完一个 Android 本地音乐播放器,这些坑替你踩了
android
hai_android4 小时前
InputStage 责任链核心执行流程
android·android studio·android jetpack
mmsx7 小时前
Android 测绘计算工程化:七四参数、高程拟合与单位系统
android·kotlin
我是场9 小时前
我的NPI项目之-Touch的EE特性
android·arm开发
天空之城--9 小时前
Android一周动态:AI编程、Compose与车载生态新信号
android·flutter
恋猫de小郭10 小时前
Dart 4.0 要彻底移除 dart:mirrors,Augmentations 应该要来了
android·前端·flutter
Carson带你学Android11 小时前
Gemini 4 Argon 发布:对 Android 开发者意味着什么?
android·ai编程
事圆则缓12 小时前
Kotlin Flow、StateFlow、SharedFlow 全解析:冷流、热流与 Android 状态管理
android·kotlin·php
应用市场12 小时前
把旧 Pixel 变成相册备份中转站(上):Mac 到安卓的照片传输工具设计——流式上传、sha256 校验、adb forward 与 Bonjour
android·macos·adb·kotlin·swift
墨天梦13 小时前
B08_Fragment事务通信与双生命周期
android