我正在使用以下代码启动一个前台服务
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
这将启动一个前台服务。在Android Oreo及以上版本中,我们必须在5秒内调用startForeground()
方法。现在在我的服务中,我们做一些处理,如果某些条件没有得到满足,那么我就不调用startForeground()
方法。相反,我试图杀死这个服务。
if (someConditionMet) {
startForeground(notificationId, notification)
} else {
stopSelf()
现在,如果someConditionMet
变量为假,那么我的应用程序就会崩溃,崩溃日志如下。
2019-04-10 16:57:25.695 19785-19785/com.awesomedroidapps.foregroundactivity E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.awesomedroidapps.foregroundactivity, PID: 19785
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e78d43f u0 com.awesomedroidapps.foregroundactivity/.ForegroundServiceTest}
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1835)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
我不明白,当我停止服务时,为什么要调用startForeground()
方法?有什么方法可以让我们在不调用startForeground()
方法的情况下停止前台服务吗?