在Android 9(Pie)版本中,引入了一个新的限制,即在启动前台服务(Foreground Service)时,必须调用startForeground()
方法,以在通知栏显示一个通知。如果没有调用此方法,将会抛出Context.startForegroundService() did not then call Service.startForeground():
的错误。
要解决此问题,请按照以下步骤操作:
onCreate()
方法中,添加以下代码来创建通知通道(Notification Channel):if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
startForegroundService()
方法之后,立即调用startForeground()
方法,并传入一个通知ID和通知对象,如下所示:Intent serviceIntent = new Intent(context, YourService.class);
ContextCompat.startForegroundService(context, serviceIntent);
// ...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// ...
startForeground(1, createNotification());
// ...
return START_STICKY;
}
private Notification createNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle("Foreground Service")
.setContentText("Service is running...")
.setSmallIcon(R.drawable.ic_notification);
return builder.build();
}
请确保通知ID和通知对象的参数与startForeground()
方法一致。
通过这样的修改,你的应用程序将能够在Android 9(Pie)及更高版本上正确启动前台服务,并显示相应的通知。