JobService is started without (or before?) calling Application onCreate

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!

1 Like

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.

2 Likes

“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?

Yes, I think I mis-wrote that. I think that the sequence of events is:

  • Your Application is called with attachBaseContext()
  • Any registered and enabled ContentProvider classes get instantiated, invoking their constructors
  • Your ContentProvider objects are called with onCreate()
  • Your Application is called with onCreate()