更新到Android 8.1后startForeground错误:应用因ForegroundServiceDidNotStartInTimeException崩溃
大家好!我是一名使用Kotlin的Android开发新手。将设备更新到Android 8.1(Oreo)后,我的应用在启动后台服务时崩溃并报错。之前在Android 7.0上一切运行正常。
以下是我的服务代码:
```kotlin
class MyForegroundService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = Notification.Builder(this, "my_channel")
.setContentTitle("服务正在运行")
.setContentText("正在执行下载...")
.setSmallIcon(R.drawable.ic_notification)
.build()
startForeground(1, notification)
// ... 长时间的后台任务
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
}
```
以下是我从Activity启动服务的方式:
```kotlin
startService(Intent(this, MyForegroundService::class.java))
```
日志中的错误:`android.app.ForegroundServiceDidN