I am new with Kotlin and little bit stack with intentService. Manifest shows me an error that my service doesn't contain default constructor, but inside service it looks ok and there are no errors.

下面是我的intentService:

class MyService : IntentService {

    constructor(name:String?) : super(name) {
    }

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

    override fun onHandleIntent(intent: Intent?) {
    }
}

I was also try another variant:

class MyService(name: String?) : IntentService(name) {

但是,当我try 运行此服务时,仍然收到错误:

java.lang.Class<com.test.test.MyService> has no zero argument constructor

有没有办法修复Kotlin中的默认构造函数?

Thanks!

推荐答案

正如所解释的here,您的服务类需要有无参数的构造器.将您的实施更改为示例中的:

class MyService : IntentService("MyService") {
    override fun onCreate() {
        super.onCreate()
    }

    override fun onHandleIntent(intent: Intent?) {
    }
}

IntentService上的Android文档声明此名称仅用于调试:

name String:用于命名工作线程,仅对调试很重要.

虽然没有明确说明,但在提到的文档页面上,框架需要能够实例化您的服务类,并希望有一个无参数构造函数.

Kotlin相关问答推荐

如何在Kotlin中反射多个对象以查找特定类型的属性

判断字符串是否除了.&" ",","@""""

将基于注册的服务转换为流

Android Studio中的只读集合不支持操作失败的原因是什么?

Scala性状线性化等价于Kotlin

扩展属性委托给实例属性

Kotlin supervisorScope 即使包裹在 try catch 中也会失败

Eclipse:无法安装 Kotlin 插件

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

如何在主线程上使用 Kotlin 协程 await()

如何在 kotlin 中生成 json 对象?

如何设置两列recyclerview?

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

Kotlin默认使用哪种排序?

取消信号上的kotlin流量采集

未在IntelliJ IDEA上运行临时文件

Kotlin-通过与属性列表进行比较来筛选对象列表

(kotlin的Moshi)@Json vs@field:Json

Kotlin for assertThat(foo, instanceOf(Bar.class))