【问题标题】:Default constructor for IntentService (kotlin)IntentService (kotlin) 的默认构造函数
【发布时间】:2017-04-08 10:49:18
【问题描述】:

我是 Kotlin 的新手,并且对 intentService 有一点点堆栈。清单向我显示了一个错误,即我的服务不包含默认构造函数,但在服务内部它看起来不错并且没有错误。

这是我的意图服务:

class MyService : IntentService {

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

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

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

我也在尝试另一种变体:

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

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

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

任何想法如何修复 Kotlin 中的默认构造函数?

谢谢!

【问题讨论】:

    标签: android kotlin intentservice android-intentservice


    【解决方案1】:

    正如here 解释的那样,您的服务类需要有无参数构造函数。将您的实现更改为示例:

    class MyService : IntentService("MyService") {
        override fun onCreate() {
            super.onCreate()
        }
    
        override fun onHandleIntent(intent: Intent?) {
        }
    }
    

    IntentService 上的 Android 文档指出此名称仅用于调试:

    nameString:用于命名工作线程,仅对调试重要。

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

    【讨论】:

      猜你喜欢
      • 2018-04-23
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 2016-07-23
      • 2019-08-09
      • 2023-03-20
      • 2016-06-29
      相关资源
      最近更新 更多