Anas Salman
Anas Salman

Reputation: 372

When IntentService starts does Application object start?

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

Answers (1)

David Wasser
David Wasser

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:

  • Creates a new Application instance (which will call the constructor of that class)
  • Calls onCreate() on the new Application instance

After 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):

  • Create new instance of Application (calling constructor of Application)
  • Call Application.onCreate()
  • Create new instance of IntentService (calling constructor of IntentService)
  • Call 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

Related Questions