Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to a Service if exists

I'm working on a project that needs an activity to connect to a local service if that service is running and start it if it is not running. What is the suitable flag for such approach.

like image 650
Mr.Me Avatar asked Feb 17 '12 12:02

Mr.Me


1 Answers

This is simply accomplished by, for instance, passing 0 in the last parameter to #bindService(Intent, ServiceConnection, int).

E.g.

bindService(new Intent(this, MrMeService.class), new ServiceConnection(){
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("Service disconnected");
        }
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("Service connected");
        }
    }, 0);

The #bindService(..) call will return true but the service will not actually start and your service connection will not trigger until someone actually starts the service, e.g. using #startService(Intent). At least this is how it works on ICS and Gingerbread.

like image 175
Jens Avatar answered Sep 17 '22 16:09

Jens