我收到一个对我来说没有意义的错误
我得到的错误是
RemoteServiceException:Context.startForegroundService() 没有然后 调用Service.startForeground()
我有一个广播接收器,它从精确的警报中脱颖而出,并且该接收器启动一项服务来完成一些简短的工作
override fun onReceive(context: Context, intent: Intent) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
context.startForegroundService(Intent(context, RestartService::class.java))
}else{
context.startService(Intent(context, RestartService::class.java))
}
}
然后在我的服务类中,我确保启动前台
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create a new notification channel
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
// Create a notification
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(content)
.setSmallIcon(R.mipmap.app)
.build()
// Start the service in the foreground
startForeground(NOTIFICATION_ID, notification)
return START_NOT_STICKY
}
如你所见,我在 onStartCommand 中调用
startForeground
我知道后台限制,但为了测试,我已启用我的应用程序
Draw over other apps
,文档说这将允许我在应用程序处于后台时启动服务和活动,并且这来自精确的警报。当应用程序也位于前台时,会发生此错误
我不知道我在这里错过了什么
看起来我在
onCreate
中的代码完成得太快,并且在我停止服务导致异常之前,服务无法调用startForeground
这个bug太烦人了。就我而言,问题是我启动了服务并在操作系统向用户显示通知之前立即停止了它。通过避免立即停止服务,您可以解决此问题。另外,您可以通过重写服务的 onDestroy 方法来检查这一点。