可以在代码中使用启动前台服务(startForegroundService)方法代替启动服务(startService)方法。
示例代码:
// 使用startForegroundService方法启动服务 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(serviceIntent); } else { context.startService(serviceIntent); }
// 在服务中使用startForeground方法开启前台服务 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("Service is running foreground")
.build();
startForeground(1, notification);
} else { startForeground(1, new Notification()); }