在Android O中,我们有一个新的后台限制。当你试图使用startService()时,你会得到一个IlleagalStateException异常,所以现在你应该使用startForegroundService(),但是如果你通过这种新的方法启动服务,你会像屏幕截图上那样出现错误。为了避免这个异常,在startForegroundService()之后你有5秒钟时间来使用startForeground()通知用户,你正在后台工作。所以,在Android O中只有一种方法:context.startForegroundService(intent) 在服务的onCreate()方法中,可以像以下这样创建一个对象: startForeground(1, new Notification()); 更新 我猜测一些制造商已经在Android N上回溯了这些新的后台限制,这就是为什么您在Android N中可能会遇到相同的异常。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent); } else { context.startService(intent); }
- Hoang Duc TuanMainActivity
的onCreate
中启动了一个服务,并在服务的onCreate
和onStartCommand
中调用了startForeground
。当应用程序调用onCreate
时,它应始终处于前台状态。但是我仍然收到这个错误。 - Kimi Chiu