By referring to bindService (Intent service, ServiceConnection conn, int flags)
May I know, when should we use 0 for flags
, and when should we should we use
For method bindService(Intent, ServiceConnection, flag)
if flag = Context.BIND_AUTO_CREATE
is used it will bind the service
and start the service,
but if "0"
is used, method will return true and will not start service until a call like startService(Intent)
is made to start the service
.
One of the common use of "0"
is in the case where an activity to connect to a local service if that service is running, otherwise you can start the service.
Semantically, use BIND_AUTO_CREATE
if you're binding to a service whose lifetime is only valid for as long as it has clients bound to it. That's because the minute all clients have unbound from it, it will go down.
Do not use BIND_AUTO_CREATE
- or perhaps I should rephrase: there's no point in using BIND_AUTO_CREATE
, if you're really just temporarily binding to a service in order to query or control it, and it is reasonable that this service would live on after you're done. For those cases, binding is for establishing a connection, and the service' lifecycle should be managed using startService()
and stopService()
(or stopSelf()
in some cases).
A commonly mentioned example of the latter case is clearly described by Google in the docs on bound services:
"... For example, a music player might find it useful to allow its service to run indefinitely and also provide binding. This way, an activity can start the service to play some music and the music continues to play even if the user leaves the application. Then, when the user returns to the application, the activity can bind to the service to regain control of playback."
Overall, I would say that the usage of the flag really distinguishes two very different types of use cases, rather than fine-tuned versions of the same thing.