Reputation: 372
I want to understand Application
object lifecycle in Android
, especially with IntentService
.
If IntentService
starts, does Application
object start along with it? And what is the exact sequence for this? Finally, when will it be destroyed in this case?
Upvotes: 4
Views: 856
Reputation: 95618
The Application
instance is a singleton. Whenever Android creates an OS process to host an Android component (Activity, Service, BroadcastReceiver, Provider
) of an application, it performs the following:
Application
instance (which will call the constructor of that class)onCreate()
on the new Application
instanceAfter that, Android then instantiates the necessary component (which calls the constructor for that component) and then calls onCreate()
on that component.
In the example of IntentService
, you should see the following (in order):
Application
(calling constructor of Application
)Application.onCreate()
IntentService
(calling constructor of IntentService
)IntentService.onCreate()
If your IntentService
completes and is stopped, Android will eventually call onDestroy()
on the IntentService
instance. At this point, if there are no other active components in the OS process, Android may decide to kill the OS process, or it may leave the OS process around for awhile.
If Android needs to start your IntentService
again and there is still a live OS process for your application, Android will not create a new OS process it will just reuse the existing one. In this case, the Application
instance already exists, so Android does not need to instantiate a new one. Android just creates a new instance of IntentService
, calls IntentService.onCreate()
and starts the IntentService
.
The Application
instance is never destroyed. When Android wants to shutdown the OS process hosting your application, it just kills the process.
Upvotes: 7