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

Android重启后onReceive()触发失败,如何实现开机通知?

解决开机触发BroadcastReceiver并发送通知的问题

一、修复Manifest配置错误

你当前的BootReceiver配置存在两个关键问题:

  • android:exported="false":ACTION_BOOT_COMPLETED是系统发送的隐式广播,必须将exported设为true,否则系统无法触发你的接收器。
  • 缺少RECEIVE_BOOT_COMPLETED权限:没有这个权限,应用无法接收开机广播。

修正后的Manifest代码:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver android:name=".BootReceiver" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

二、安卓新版本下onReceive()生效的前提

  • Android 12+(API 31):静态注册的BroadcastReceiver接收开机广播,要求应用必须被用户至少手动启动过一次,且未被系统禁用或强制停止。如果用户从未打开过应用,静态广播不会触发。
  • ACTION_USER_PRESENT注意:从Android 10(API 29)开始,这个广播不支持静态注册,只能在应用运行时通过registerReceiver()动态注册。如果需要用户解锁后触发逻辑,要在应用启动时完成动态注册。

三、开机后发送通知的实现

Android 8.0(API 26)及以上必须创建通知渠道,否则通知无法正常显示。

1. BootReceiver中的通知代码示例

public class BootReceiver extends BroadcastReceiver {
    private static final String BOOT_CHANNEL_ID = "boot_ready_channel";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_BOOT_COMPLETED.equals(action) || Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) {
            // 创建通知渠道(适配Android 8.0+)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(
                        BOOT_CHANNEL_ID,
                        "开机就绪通知",
                        NotificationManager.IMPORTANCE_DEFAULT
                );
                channel.setDescription("设备开机后告知应用状态");
                NotificationManager manager = context.getSystemService(NotificationManager.class);
                manager.createNotificationChannel(channel);
            }

            // 构建通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, BOOT_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_app_notification) // 替换为你的通知图标
                    .setContentTitle("应用已就绪")
                    .setContentText("设备开机完成,现在可以使用应用了")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);

            // 发送通知
            NotificationManagerCompat.from(context).notify(1001, builder.build());
        }
    }
}

2. 额外注意点

  • 通知图标必须符合安卓规范:避免使用纯白色图标,否则在深色模式或部分系统中会显示异常。
  • 若通过LOCKED_BOOT_COMPLETED触发,此时设备处于锁定状态,通知会根据用户的锁屏设置显示(可能需要用户解锁后才能查看详情)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:12:23