Avatar ·

更新到Android 8.1后startForeground错误:如何修复?

大家好!我正在开发一个使用Kotlin编写的应用程序,它利用后台服务来跟踪位置。在设备更新到Android 8.1(Oreo)后,我的服务停止工作并抛出错误`Context.startForegroundService() did not then call Service.startForeground()`。以下是我的服务代码: ```kotlin class LocationService : Service() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val notification = NotificationCompat.Builder(this, "channel_id") .setContentTitle("服务活跃") .setContentText("位置跟踪") .setSmallIcon(R.drawable.ic_location) .build() startForeground(1, notification) return START_STICKY } override fun onBind(intent: Intent?): IBinder? = null } ``` 并且我这样启动它: ```kotlin val intent = Intent(this, LocationService::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {