gpt4 book ai didi

android - 服务错误 "... has no zero argument constructor"

转载 作者:行者123 更新时间:2023-12-05 00:11:16 25 4
gpt4 key购买 nike

我想启动一个服务,我使用:

inner class HomeService : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}

override fun onCreate() {
super.onCreate()
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
notification(light.toString())
return START_STICKY
}

override fun onDestroy() {
super.onDestroy()
}
}

启动它:

val i = Intent(this@Main3Activity, HomeService()::class.java)
startService(i)

在我的应用程序崩溃后,logcat 返回:

java.lang.Class has no zero argument constructor at android.app.ActivityThread.handleCreateService(ActivityThread.java:3201) at android.app.ActivityThread.-wrap5(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1586) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6186) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) Caused by: java.lang.InstantiationException: java.lang.Class has no zero argument constructor at java.lang.Class.newInstance(Native Method) at android.app.ActivityThread.handleCreateService(ActivityThread.java:3198) at android.app.ActivityThread.-wrap5(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1586)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6186)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

我该怎么办?

最佳答案

您通过在 Intent 创建代码中写下 HomeService() 来手动创建一个实例。创建服务是框架的任务,你可以在不创建实例的情况下传递它的类:

val i = Intent(this@Main3Activity, HomeService::class.java)
startService(i)

更新:

除上述之外,你的类也不能是内部类。它可以嵌套,但不能是内部类,因为它们持有对它们所在类的引用。这意味着系统无法自行创建您的服务实例 - 它无法提供外部类供其引用。

关于android - 服务错误 "... has no zero argument constructor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51057471/

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