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

设备重启时启动Service的实现咨询:含广播接收器代码与权限配置

Hey there! Let's get your boot-up Service working properly. I'll walk you through completing the implementation and troubleshooting common pitfalls below:

1. Complete AndroidManifest.xml Configuration

You're missing a few critical entries in your manifest to make the boot broadcast work. Here's what you need to add:

<!-- Add the required boot permission -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<!-- Register your MyService (if not already done) -->
<service android:name=".MyService" />

<!-- Properly register your broadcast receiver with the boot intent filter -->
<receiver android:name=".StartServiceReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <!-- For Android 12+, add this to handle delayed boot broadcasts -->
        <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
    </intent-filter>
</receiver>
2. Adapt to Android 8.0+ Background Restrictions

Starting from Android 8.0 (API 26), direct startService() calls from background contexts (like a broadcast receiver) will throw an IllegalStateException. You need to use startForegroundService() instead, and your Service must show a foreground notification immediately:

Update Your Broadcast Receiver Code

public class StartServiceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("TEST", "Boot completed, initiating service start");
        Intent serviceIntent = new Intent(context, MyService.class);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(serviceIntent);
        } else {
            context.startService(serviceIntent);
        }
    }
}

Add Foreground Notification Logic to MyService

public class MyService extends Service {
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "BOOT_SERVICE_CHANNEL";

    @Override
    public void onCreate() {
        super.onCreate();
        // Create notification channel for Android 8.0+
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "Boot Service Channel",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
        // Launch foreground service with a minimal notification
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Service Running")
                .setContentText("Started automatically after boot")
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
        startForeground(NOTIFICATION_ID, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
3. Troubleshooting Common Issues
  • Broadcast Receiver Not Triggering:
    • Ensure your app has been manually launched at least once (Android 3.1+ blocks boot broadcasts for apps that have never been opened by the user).
    • Check if your app is excluded from battery optimization—many OEMs restrict background actions for unoptimized apps.
    • Verify the BOOT_COMPLETED action in your intent filter is spelled correctly.
  • Service Fails to Start:
    • For Android 13+ (targetSdk >= 33), you need to request the POST_NOTIFICATIONS permission dynamically, otherwise the foreground notification will fail and the service will be killed:
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
          if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
              registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                  // Handle permission grant result
              }).launch(Manifest.permission.POST_NOTIFICATIONS);
          }
      }
      
  • OEM-Specific Restrictions:
    • Xiaomi, Huawei, OPPO, and other manufacturers have strict background management. You'll need to guide users to add your app to the "Auto-start" whitelist in their system settings.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:00:26