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

案例代码

相关推荐
好的佩奇15 小时前
蓝牙之设备角色与连接
android·flutter·蓝牙
雨白1 天前
Android 消息机制剖析:从 Handler 投递到 Looper 循环的全链路
android
GY-931 天前
【Android】数据分层和依赖注入
android
传奇开心果编程1 天前
【Jetpack Compose娓娓道来】第44课:持久化——让数据“关掉App也不丢”
android·kotlin·移动开发·数据持久化·jetpack compose·ui框架·声明式ui
星空孤辰1 天前
【camera 008】android camera id 注册、状态监控等状态变化 全流程梳理
android·windows
恋猫de小郭1 天前
iOS for Web ,把原生 iOS App 跑到进浏览器里面,倒反天罡
android·前端·ios
思想觉悟1 天前
Android启动流程之点rc文件
android·linux·面试
_祝你今天愉快2 天前
Android 高级绘制:[四] Canvas-实际案例操作
android
三少爷的鞋2 天前
Android 工程师的技术信仰崩塌史
android
AirDroid_cn2 天前
Android 15 权限回溯:已授予的麦克风权限如何批量回收?
android