我已经开始这样的服务了:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
但是当我想要停止这项服务时,我遇到了一个错误:
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6501)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
为了解决这个错误我试过:1。在onDestroy()方法中使用stopSelf();
。 2.在onCreate()方法中使用startForeground(0, new Notification());
。
但错误仍然存在。我在StackOverflow和Android官方网站上搜索了很多。找不到合适的答案来解决我的问题。顺便说一句,此错误从Android OREO版本开始。
正如提到的here
“Android 8.0引入了新方法startForegroundService()以在前台启动新服务。在系统创建服务之后,应用程序有五秒钟来调用服务的startForeground()方法来显示新服务的用户可见通知。如果应用程序未在时间限制内调用startForeground(),系统将停止该服务并将该应用程序声明为ANR。“