Android 10 应用收不到BOOT_COMPLETED广播无法启动服务
问题原因
Android 8.0(API 26)及以上版本引入了后台执行限制,结合你应用的无Activity特性,触发问题的核心原因有3个:
- 无Activity的应用安装后默认处于系统的停止状态,停止状态的应用默认无法接收任何系统广播
- 你注册了
LOCKED_BOOT_COMPLETED广播(直启动模式下的广播),但接收器BootReceiver没有配置directBootAware="true",不符合直启动广播的接收要求 - 广播接收器属于临时组件,执行完
onReceive后应用会回归后台状态,此时直接启动普通后台服务会被系统拦截
解决方案
按以下步骤逐一修改即可解决:
修正清单文件配置
给BootReceiver补充directBootAware属性,和服务的直启动配置保持一致:<receiver android:name=".BootReceiver" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" android:exported="true" android:directBootAware="true" > <intent-filter android:priority="999"> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" /> </intent-filter> </receiver>若你不需要在用户未解锁设备时就运行服务,可以删除
LOCKED_BOOT_COMPLETED的action配置,也不用加directBootAware属性。解决应用停止状态问题
没有Activity的应用无法通过用户点击启动触发停止状态解除,按部署场景选择方案:- 若应用是系统预装应用:放在
/system/priv-app分区下,系统会自动解除停止状态,无需额外处理 - 若应用是普通用户安装:安装时执行adb命令
adb install -r --dont-kill 你的APK路径,安装后应用不会进入停止状态
- 若应用是系统预装应用:放在
广播接收后启动前台服务而非普通后台服务
在BootReceiver的onReceive方法中,不要调用startService,改用兼容方法启动前台服务:@Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) || Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(intent.getAction())) { Intent serviceIntent = new Intent(context, HttpUpdateService.class); // 安卓8.0及以上用前台服务方式启动 ContextCompat.startForegroundService(context, serviceIntent); } }同时必须在
HttpUpdateService的onCreate方法中5秒内调用startForeground展示前台服务通知,否则会触发ANR:@Override public void onCreate() { super.onCreate(); // 安卓8.0及以上需要创建通知渠道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID", "服务运行通知", NotificationManager.IMPORTANCE_LOW); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } Notification notification = new NotificationCompat.Builder(this, "YOUR_CHANNEL_ID") .setContentTitle("服务正在运行") .setContentText("Http更新服务已启动") .setSmallIcon(R.mipmap.ic_launcher) .build(); // 启动前台服务,ID不能为0 startForeground(1001, notification); }若适配Android 13及以上版本,需要额外在清单文件中添加通知权限:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
内容的提问来源于stack exchange,提问作者Rahul Giradkar
相关产品推荐
相关产品推荐

