0

Stackoveflow!

I have an application with sticky background service and visible part, consisted of several activities.

I need to track start and stop of visible part (all activities). For example:

  • When user starts MainActivity, Service receives LocalBroadcast that tells it to start something.
  • When user rotates screen, Service must not receive anything.
  • When user goes to SecondActivity, Service again must not receive anything.
  • When user closes ALL ACTIVITIES, Service gets LocalBroadcast telling it to stop something.

If I use Activity. onCreate and onDestroy, or onStart and onStop, I get events related to lifecycle of single activity. Also I get events related to screen rotation.

I also cannot use Application. onCreate or onTerminate, as they will not trigger because of service running in the background.

I need to track real start and stop of entire application except service.

Egor
  • 435
  • 5
  • 17

1 Answers1

1

See: http://developer.android.com/guide/components/bound-services.html

When the last client unbinds from the service, the system destroys the service (unless the service was also started by startService()).

So each Activity should bind() to the service, in onCreate, and unbind() in onStop/onDestroy

Now to fix the problem with the orientation changes, you can check for isFinishing in the onStop/onDestory callback (see: How to distinguish between orientation change and leaving application android)

and also put some flag in onSaveInstanceState callback, so that in the following onCreate you can check for the existence of that flag, and act accordingly (refresh the binding, or avoid calling bind() again)

Community
  • 1
  • 1
marmor
  • 27,641
  • 11
  • 107
  • 150