Salivan
Salivan

Reputation: 1905

What happens to the Service if the Activity is killed?

I have a Service which is started from BroadcastReceiver when a new incoming call arrives. In that Service I start a new Thread and do all the work there. What happens if the Main Activity of my app is killed? I'm asking because I realised that in such a situation the Service's startID rises by one! Just like if the Service's onStartCommand() was called again or something like that. I'll give a short example:

  1. Main Activity is running somewhere in the background, incoming call arrives, Service starts, stopSelf() is called by the user action, Service is destroyed.
  2. Main Activity is running, incoming call arrives, Service starts, Main Activity is killed by clearing Recent apps list, stopSelf() is called by the user action, Service is NOT destroyed because startIDs don't match.
  3. Main Activity is NOT running (killed by clearing Recent apps list), incoming call arrives, Service starts, stopSelf() is called by the user action, Service is destroyed.

That is very strange, because startID somehow changes its value when the Main Activity is killed. I use START_NOT_STICKY in my Service's onStartCommand() method so there is no way that Service is recreated with a new startID. Could someone explain this to me? What happens to the Service or the separate Thread where the service is running when Main Activity is killed? Thanks in advance!

Upvotes: 0

Views: 1377

Answers (1)

Jim
Jim

Reputation: 10278

Removing an activity from "recents" does not kill it. If the incoming call broadcast results in a "startService" call, a service's "onStartCommand" will be called again without a problem (Android onCreate or onStartCommand for starting service).

So, in #2 you might think your activity "died" but it didn't, and since startId changes every time the onStartCommand is called, the next request to start the service won't match any previous startId. This is the expected behavior.

Upvotes: 1

Related Questions