Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use 0 or BIND_AUTO_CREATE for bindService's flag

Tags:

android

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 BIND_AUTO_CREATE for flags? The documentation doesn't explain what is the meaning of 0 for flags.

Example for using 0 as flags

// Start auto complete service.
autoCompleteServiceIntent = new Intent(AutoCompleteService.class.getName()); 
startService(autoCompleteServiceIntent);
bindService(autoCompleteServiceIntent, serviceConnection, 0);

Example for using BIND_AUTO_CREATE as flags

mContext.bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
                             mServiceConn, Context.BIND_AUTO_CREATE);
like image 551
Cheok Yan Cheng Avatar asked Feb 07 '13 07:02

Cheok Yan Cheng


2 Answers

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.

like image 162
Sourab Sharma Avatar answered Oct 19 '22 07:10

Sourab Sharma


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.

like image 41
d4vidi Avatar answered Oct 19 '22 09:10

d4vidi