gpt4 book ai didi

java - oncreate Application 类中的 IllegalStateException

转载 作者:行者123 更新时间:2023-12-02 01:55:17 26 4
gpt4 key购买 nike

我收到错误 java.lang.RuntimeException Caused by: java.lang.IllegalStateException in super.onCreate() in android version 8.0

public final class ClockApp extends Application {
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(getApplicationContext(), MyService.class));
}
}

错误日志如下:

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)

最佳答案

从 API 26 开始,当应用不在前台时,以及在 Application.onCreate() 调用期间,您无法启动服务它仍然不在前台

引用:https://developer.android.com/guide/components/services#StartingAService

因此有一些可能的方法来解决这个问题:

  • (很好的解决方案)延迟服务启动,直到应用程序进入前台。例如 - 启动器 Activity 的 onCreate 方法。
  • (好的解决方案)使用startForegroundService()
  • (不确定是否有效,糟糕的解决方案)将 targetSDK 降级到 26 以下

关于java - oncreate Application 类中的 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52398630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com