javaandroidserviceandroid-broadcastandroid-application-class

Will Application Class OnCreate be called if a Broadcast is recieved


I am using a JobIntentService perform some task after the task is ended I send a Broadcast which is also listened by one of my Activity.

Suppose in a case where the activity is closed by Android OS to free up some memory then if the Broadcast is sent from the JobIntentService will the OnCreate of the Application also be called?


Solution

  • NO. It will never call the applications OnCreate() method (is called only during a cold start).

    A cold start refers to an app’s starting from scratch: the system’s process has not, until this start, created the app’s process. Cold starts happen in cases such as your app’s being launched for the first time since the device booted, or since the system killed the app.

    About BroadcastReceiver Lifecycle:

    If your receiver is registered in activity then it's lifecycle is the activities lifecycle. So your receiver will not be able to listen once your activity gets destroyed.

    If your receiver is registered in application then it's lifecycle will be applications lifecycle and it will be able to listen to the broadcasts as long as the application is not destroyed.

    JobIntentService & Receiver

    When you start a JobIntentServie (from a receiver) then your job intent service will not get killed by the OS as long as there is active jobs going on (please note that there may be a time limitation, to know more: How long is the "JobService execution time limit" mentioned in Android's JobIntentService docs?).

    Now if your activity is destroyed in the meantime then your broadcast receiver will not listen to the broadcast because it's lifecyle has ended, if you don't unregister the receiver yourself, the system will kill it as system considers the BroadcastReceiver to be no longer active.

    So if you want to listen to a broadcast as long as your application is not destroyed, you should register your broadcast receiver in applications onCreate() method.