JobService is started without (or before?) calling Application onCreate
from the CommonsWare Community archivesAt March 11, 2020, 12:41pm, sudokai asked:
Hi,
I’m using a JobScheduler to launch JobServices and I’m getting an NPE when I try to access my Application class’ static variables that are initialized in the Application’s onCreate method. I saw this thread in StackOverflow and I have the exact problem:
I also saw this answer by Mark in another Stackoverflow thread (https://stackoverflow.com/questions/54268524/how-can-i-keep-the-job-service-running-when-the-app-is-closed-from-recent-task-l) but the answer mentions Activities or UI elements only. I wonder if the same answer applies to a project’s main Application class.
Any solutions to this? Thanks!
At March 11, 2020, 1:58pm, mmurphy replied:
There are things that get instantiated before onCreate()
of an Application
is called. Notably, any ContentProvider
in your app will be instantiated before onCreate()
on Application
is called (and, after that, onCreate()
of each provider is called).
I am not aware of JobService
having a similar behavior, though I cannot strictly rule it out.
IMHO, having static variables in an Application
class, initialized in onCreate()
, is a code smell. Consider trying to rework your code to eliminate those variables. For example, you might use dependency inversion frameworks (Dagger, Koin, etc.) to inject the objects into the JobService
.
At April 27, 2020, 9:06am, sudokai replied:
“Notably, any ContentProvider
in your app will be instantiated before onCreate()
on Application
is called (and, after that, onCreate()
of each provider is called).”
Wait, what does this mean? ContentProviders’ onCreate is called after Application onCreate?
At April 27, 2020, 11:06am, mmurphy replied:
Yes, I think I mis-wrote that. I think that the sequence of events is:
- Your
Application
is called withattachBaseContext()
- Any registered and enabled
ContentProvider
classes get instantiated, invoking their constructors - Your
ContentProvider
objects are called withonCreate()
- Your
Application
is called withonCreate()