startForegroundService() создает исключение IllegalStateException в Oreo в приложении BOOT_COMPLETED
У меня приложение (в Android O) запустит службу после перезагрузки устройства. Как только устройство перезагружается, в методе onReceive() приемника вещания оно вызывает службу как startForegroundService() для ОС Android 8 и выше.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Внутри класса обслуживания он запускает уведомление от метода onStartCommand().
Но все равно он вызывает исключение IllegalStateException. Кто-нибудь сталкивался с подобными проблемами в Android OS 8 и выше?
2 ответа
Вы должны позвонить startForeground()
из запущенного сервиса, это в документах:
Как только служба создана, она должна вызвать свой метод startForeground() в течение пяти секунд.
Так, например, вам нужно сделать это из вашего Service
учебный класс:
@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());
}
}
Система позволяет приложениям вызывать контекст.startForegroundService(), даже если приложение находится в фоновом режиме. Однако приложение должно вызвать метод startForeground() этой службы в течение пяти секунд после создания службы.
Напишите ваш сервис onCreate как ниже.
@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);
}
}
Так что startForeground() может быть вызван в течение 5 секунд после запуска сервиса.