startForegroundService()在应用程序BOOT_COMPLETED上的Oreo中引发IllegalStateException
我拥有的应用程序(在Android O中)将在设备重启后启动服务.重新启动设备后,在广播接收器的onReceive()方法中,它将服务调用为startForegroundService()(适用于Android OS 8及更高版本).
The application I am having (in Android O) will start a service after device reboot. Once the device is rebooted, in the onReceive() method of the broadcast receiver it is calling the service as startForegroundService() for Android OS 8 and above.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
在服务类内部,它是通过onStartCommand()方法启动通知的.
Inside the service class it is starting the notification from the onStartCommand() method.
但是它仍然抛出IllegalStateException.在Android OS 8及更高版本中,有人遇到过类似的问题吗?
But still it is throwing the IllegalStateException. Did someone faced similar issues in Android OS 8 and above?
您必须从已启动的服务中调用startForeground()
,它在文档中:
You have to call startForeground()
from the started service, it's in the docs:
创建服务后,该服务必须在五秒钟内调用其startForeground()方法.
Once the service has been created, the service must call its startForeground() method within five seconds.
例如,您需要在Service
类中执行此操作:
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());
}
}