startForegroundService() is throwing IllegalStateException in Oreo on app BOOT_COMPLETED

笑着哭i 提交于 2019-12-06 16:48:43

You have to call startForeground() from the started service, it's in the docs:

Once the service has been created, the service must call its startForeground() method within five seconds.

Source

So for example you need to do this from your Service class:

@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String CHANNEL_ID = "channel_01";
        String CHANNEL_NAME = "Channel Name";

        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        channel.setSound(null, null);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);

        Builder notification = new Builder(this, CHANNEL_ID).setSound(null).setVibrate(new long[]{0});
        notification.setChannelId(CHANNEL_ID);

        startForeground(1, notification.build());
    }
} 

The system allows apps to call Context.startForegroundService() even while the app is in the background. However, the app must call that service's startForeground() method within five seconds after the service is created.

Write your service's onCreate like below.

@Override
 public void onCreate() {
    super.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "my_channel_01";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build();

        startForeground(1, notification);
    }
 }

So that startForeground() can be called within 5 seconds of starting the service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!