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

案例代码

相关推荐
救救孩子把28 分钟前
结构化输出为何“格式正确、答案错误”?JSON Schema 的能力边界
android·java·json·agent·agent服务
张小姐的猫1 小时前
【MySQL】事务
android·mysql·adb
你看我名字1 小时前
数眼智能 Search + Reader 实战:联网问答怎样避免“搜到了,却引用错了”
android·java·开发语言
恋猫de小郭2 小时前
最近 Android 有什么更新:Android Dev Summit 2026 技术解读
android·前端·flutter
Kapaseker2 小时前
删掉 1.1 万行 C 代码,Rust 正式接手 Android Binder
android·rust
嵌入式-老费3 小时前
esp32开发与应用(题外话之ADB和Android NDK开发)
android·adb
野生的码农3 小时前
能工智人,40 大寿,尚能班否?
android·ai编程
事圆则缓3 小时前
Android 串口通信:从 /dev/ttyS1到协议帧
android
java1234_小锋3 小时前
【技术专题】CSS3 网页技术 - CSS3 基础样式
android·前端·css3
tongyiixiaohuang13 小时前
WMS已发货状态反写金蝶云星空:单策略实战教程
android