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 分钟前
Android项目架构深度解析
android
丐中丐99937 分钟前
一个Binder通信中的多线程同步问题
android
诸神黄昏EX41 分钟前
Android Qualcomm USB 专题系列【篇二:UsbGadget模式配置】
android
vocal42 分钟前
【我的AOSP第一课】Android Init 语言与 rc 文件
android
诸神黄昏EX1 小时前
Android Qualcomm USB 专题系列【总篇:USB HAL架构】
android·linux·网络
原神启动11 小时前
Ansible(三)—— 使用Ansible自动化部署LNMP环境
android·自动化·ansible
前端老白2 小时前
webview在微信小程序中,安卓加载失败,IOS正常加载
android·ios·微信小程序·webview
2501_937154932 小时前
适配中兴主流机型 纯净版刷机固件技术优势合集
android·源码·源代码管理·机顶盒
2501_915106322 小时前
用 HBuilder 上架 iOS 应用时如何管理Bundle ID、证书与描述文件
android·ios·小程序·https·uni-app·iphone·webview
TheNextByte12 小时前
如何通过OTG或不使用OTG将文件从Android传到U盘
android