问题
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);
}
Inside the service class it is starting the notification from the onStartCommand() method.
But still it is throwing the IllegalStateException. Did someone faced similar issues in Android OS 8 and above?
回答1:
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());
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/53081249/startforegroundservice-is-throwing-illegalstateexception-in-oreo-on-app-boot-c