IllegalAccessException when enqueueing work with WorkManager
Asked Answered
U

1

5

I get IllegalAccessException when trying to enqueue work with WorkManager 1.0 stable. Here's the stack trace:

E/WM-WorkerFactory: Could not instantiate com.pocket.sdk.util.service.BackgroundSync$SyncJob
    java.lang.IllegalAccessException: java.lang.Class<com.example.BackgroundManager$BackgroundWorker> is not accessible from java.lang.Class<androidx.work.WorkerFactory>
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:92)
        at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:233)
        at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:127)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)

The worker is an inner class declared like so:

private static class BackgroundWorker extends Worker {
    // ...
}

How can I fix this exception?

Ultimate answered 12/3, 2019 at 11:35 Comment(0)
U
6

Looks like WorkManager is using reflection to create an instance of the worker. However because it is declared as a private inner class it is inaccessible to the WorkerFactory class that tries to do this.

What I've done is to simply declare my workers as public inner classes, like so:

public static class BackgroundWorker extends Worker {
    // ...
}

I have also made sure that the constructor is public.

But I would love to find a solution that doesn't require exposing the workers to the whole world.

Ultimate answered 12/3, 2019 at 11:35 Comment(1)
You could look into creating your own WorkerFactory.Billye

© 2022 - 2024 — McMap. All rights reserved.