4

WorkManager 1.0.0-alpha02在依赖项中使用 foundandroid.arch.work:work-runtime每隔一分钟查询一个网页(此示例排除了查询代码,因为它无关紧要)。

当我WorkManager这样使用时:

WorkManager
                .getInstance()
                .enqueue(
                        new PeriodicWorkRequest.Builder(
                                MessageWorker.class,
                                1,
                                TimeUnit.MINUTES
                        )
                                .setConstraints(
                                        new Constraints.Builder()
                                                .setRequiredNetworkType(NetworkType.CONNECTED)
                                                .build()
                                )
                                .build()
                );

private class MessageWorker extends Worker {
        public MessageWorker() {
        }

        @NonNull
        @Override
        public WorkerResult doWork() {
            // Do stuff
            return WorkerResult.SUCCESS;
        }
}

它给出了这个错误信息:

05-31 17:50:05.645 11749-12168/com.neelkamath.webview E/WorkerWrapper: Trouble instantiating com.neelkamath.webview.MainActivity$MessageWorker
    java.lang.InstantiationException: java.lang.Class<com.neelkamath.webview.MainActivity$MessageWorker> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.work.impl.WorkerWrapper.workerFromClassName(WorkerWrapper.java:405)
        at androidx.work.impl.WorkerWrapper.workerFromWorkSpec(WorkerWrapper.java:377)
        at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:132)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
05-31 17:50:05.645 11749-12168/com.neelkamath.webview E/WorkerWrapper: Could for create Worker com.neelkamath.webview.MainActivity$MessageWorker

我尝试了以下构造函数无济于事:

  • 没有构造函数
  • 上市
  • 私人的
  • 具有非空主体的构造函数,其唯一语句为super();
4

2 回答 2

2

从 MessageWorker 中删除以下构造函数并创建类public。:

public MessageWorker() {
}

还要确保类在单独的文件中。

于 2018-05-31T12:51:10.543 回答
1

您可以在单独的文件中创建 MessageWorker 类,如果您想将 MessageWorker 类作为嵌套类,您也可以这样static

public static class MessageWorker extends Worker {
    @NonNull
    @Override
    public WorkerResult doWork() {
        // Do stuff
        return WorkerResult.SUCCESS;
    }
}

原因是 WorkerWrapper 将创建您的工作实例clazz.newInstance(),并且嵌套类没有零参数构造函数

于 2018-07-06T02:53:01.130 回答