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

案例代码

相关推荐
韩曙亮1 小时前
【Flutter】Flutter 进程保活 ③ ( 屏幕常亮设置 | Flutter 禁止息屏、关闭自动锁屏、屏蔽系统屏保 )
android·flutter·ios·屏幕常亮·禁止息屏
爱笑鱼2 小时前
NDK、SDK、APP、Framework、Native 到底怎么区分?
android
私人珍藏库2 小时前
[Android] 发票制作器-内置多行业专业模板
android·人工智能·app·软件·多功能
悲凉的紫菜4 小时前
dariy
android·ide·android studio
2501_915909064 小时前
IPA 深度混淆是什么意思?从混淆强度到实际效果的解读
android·ios·小程序·https·uni-app·iphone·webview
LT10157974445 小时前
2026年手机机型兼容性测试选型指南:安卓机型碎片化、APP闪退UI错乱如何解决
android·测试工具·ui·智能手机
阿pin6 小时前
Android随笔-view是如何显示到屏幕上
android·view
恋猫de小郭6 小时前
Flutter material/cupertino 解耦最新进展,已经在做新样式了
android·前端·flutter
在书中成长7 小时前
HarmonyOS 小游戏《对战五子棋》开发第17篇 - AI的两种评估策略
android·java·javascript
私人珍藏库7 小时前
[Android] Npatch-免Root框架+可内置模块
android·人工智能·智能手机·工具·软件