You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮无响应,Toast与BroadcastReceiver不生效问题求助

问题原因

  1. Android 8.0(API 26)及以上系统对静态注册的隐式广播做了限制,仅携带action的隐式广播默认会被系统拦截,无法触发静态注册的BroadcastReceiver。
  2. 你当前发送的广播仅设置了action属性,属于隐式广播,同时MyReceiver在清单文件中配置了android:exported="false",隐式发送时无法匹配到该Receiver。

解决方案

任选以下任意一种方案修改即可:

方案1:发送显式广播(推荐,性能更高,匹配更准确)

修改MainActivity.java中的broadcastIntent方法,直接指定要触发的Receiver类:

// broadcast a custom intent.
public void broadcastIntent(View view){
    Intent intent = new Intent(MainActivity.this, MyReceiver.class);
    intent.setAction("com.myapplication.BOOT_COMPLETED");
    sendBroadcast(intent);
}

方案2:给隐式广播指定应用包名

修改MainActivity.java中的broadcastIntent方法,给Intent添加当前应用的包名标识,让系统识别为应用内广播,跳过拦截规则:

// broadcast a custom intent.
public void broadcastIntent(View view){
    Intent intent = new Intent();
    intent.setAction("com.myapplication.BOOT_COMPLETED");
    intent.setPackage(getPackageName());
    sendBroadcast(intent);
}

可选优化项

修改AndroidManifest.xml中MyReceiver的name属性,添加前缀.,避免部分编译环境无法匹配到同包下的Receiver类:

<receiver android:name=".MyReceiver"
    android:exported="false">
    <intent-filter>
        <action android:name="com.myapplication.BOOT_COMPLETED">
        </action>
    </intent-filter>
</receiver>

修改完成后重新编译安装应用,点击按钮即可正常触发Receiver弹出Toast。

内容的提问来源于stack exchange,提问作者Alice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:24:03