oncreate应用程序类中的IllegalStateException

时间:2018-09-19 05:22:19

标签: java android

我收到了java.lang.RuntimeException错误,原因是:android版本8.0中的super.onCreate()中的java.lang.IllegalStateException

java.lang.RuntimeException: 
  at android.app.ActivityThread.handleBindApplication (ActivityThread.java:6065)
  at android.app.ActivityThread.-wrap1 (Unknown Source)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1764)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:164)
  at android.app.ActivityThread.main (ActivityThread.java:6942)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327) 
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)

Caused by: java.lang.IllegalStateException: 
  at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1538)
  at android.app.ContextImpl.startService (ContextImpl.java:1484)
  at android.content.ContextWrapper.startService (ContextWrapper.java:663)
  at com.alarm.speakingclock.ClockApp.onCreate (ClockApp.java:14)
  at android.app.Instrumentation.callApplicationOnCreate (Instrumentation.java:1126)
  at android.app.ActivityThread.handleBindApplication (ActivityThread.java:6062)
  at android.app.ActivityThread.-wrap1 (Unknown Source)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1764)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at android.os.Looper.loop (Looper.java:164)
  at android.app.ActivityThread.main (ActivityThread.java:6942)
  at java.lang.reflect.Method.invoke (Method.java) 
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)

错误日志如下:

jdbcTemplate.setFetchSize(1000);

1 个答案:

答案 0 :(得分:2)

从API 26开始,当应用程序不在前台,并且在Application.onCreate()调用期间,它仍然不在前台,您将无法启动服务。

参考:https://developer.android.com/guide/components/services#StartingAService

因此,有一些可能的方法可以解决此问题:

  • (好的解决方案)延迟服务启动,直到应用程序出现在前台。例如-启动器活动的onCreate方法。
  • (好的解决方案)使用startForegroundService()
  • (不确定是否可以使用,不好的解决方案)将targetSDK降级到26以下