4

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?

Onik
  • 19,396
  • 14
  • 68
  • 91
Anas Salman
  • 372
  • 3
  • 16

1 Answers1

7

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.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • @Onik Killing an OS process does not cause the destruction (in an object sense) of the `Application` instance. The OS just makes the process "go away". There is no guarantee that any "clean up" will actually occur. You will also notice that there is no `onDestroy()` method in the `Application` class. – David Wasser Jan 26 '16 at 16:10
  • 1
    Correct. _"Never destroyed"_, without clarification seemed confusing to me, and probably might for someone else. – Onik Jan 26 '16 at 16:13