自动生成不正确的IntentService默认构造函数

时间:2018-10-28 19:03:47

标签: android shortcut

Android Studio有一个有用的快捷方式,可以自动生成所需的构造函数并覆盖方法(alt + enter)。

对于IntentService,Android Studio在默认构造函数下方自动生成,该构造函数在AndroidManifest.xml中显示错误。

public class MyIntentService extends IntentService {

//  Auto-generated by IDE
    public MyIntentService(String name) { super(name); }

//  This is the correct default constructor!
//  public MyIntentService() { super("MyIntentService"); }

    @Override
    protected void onHandleIntent(@androidx.annotation.Nullable Intent intent) {
        ...
    }

}

AndroidManifest.xml中的错误是

  

'... MyIntentService'没有默认的构造函数

我知道如何手动更正此错误,但是IDE为什么会创建错误的构造函数?这是错误吗?是否可以在IDE中更正此错误?

1 个答案:

答案 0 :(得分:2)

这是偶然的。我不认为这是一个错误。

IntentService是具有一个构造函数IntentService(String)的抽象类。预期的用法是实现子类的构造函数调用它,以提供一个对调试有用的名称。

另一方面,Android Service必须具有无参数构造函数,以便框架可以实例化它们。它也适用于IntentService

IDE尤其不了解IntentService。它只是看到一个带有String参数的构造函数,并提供生成兼容的子类构造函数的功能。另一款Android Lint工具随后检测到清单中声明的​​Service没有no-arg构造函数,并发出警告。

请注意,根据当前的后台执行限制,最好使用JobIntentService之类的其他机制,而不是IntentService