TIMEX
TIMEX

Reputation: 271594

How do I bind this service in Android?

This is the code in my Activity. Initiate an Intent, then a Connection, right?

hello_service = new Intent(this, HelloService.class);
hello_service_conn = new HelloServiceConnection();
bindService( hello_service, hello_service_conn, Context.BIND_AUTO_CREATE);

But my question is...what goes inside the Connection?

   class HelloServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName className,IBinder boundService ) {

        }
        public void onServiceDisconnected(ComponentName className) {

        }
    };

Can someone tell me what code I put into onServiceConnected and onServiceDisconnected?

I just want a basic connection so that my Activity and Service can talk to each other.

Edit: I found a good tutorial, and I can actually close this question, unless someone wants to answer. http://www.androidcompetencycenter.com/2009/01/basics-of-android-part-iii-android-services/

Upvotes: 9

Views: 36203

Answers (3)

KnowIT
KnowIT

Reputation: 2502

To connect a service to an activity, all you need to write in a ServiceConnection implementation is :

@Override
public void onServiceDisconnected(ComponentName name) {
mServiceBound = false;
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyBinder myBinder = (MyBinder) service;
mBoundService = myBinder.getService();
mServiceBound = true;
}

Here mBoundService is an object of your bound service. Have a look at this Bound Service Example.

Upvotes: 1

Nikhil_Katre
Nikhil_Katre

Reputation: 554

Binding to a service from an Activity should be avoided as it causes probems when the Activity Configurations change (e.g. if the device is rotated the activity would get created again from scratch and the binding would have to be re-created).
Please refer to the comment from Commonsware on the following post on stackoverflow
Communicate with Activity from Service (LocalService) - Android Best Practices

Upvotes: 5

Chris.D
Chris.D

Reputation: 1516

I would like to point out that if you follow the service examples provided by google then your service will leak memory, see this chaps excellent post on how to do it properly (and vote for the related Google bug)

http://www.ozdroid.com/#!BLOG/2010/12/19/How_to_make_a_local_Service_and_bind_to_it_in_Android

Upvotes: 16

Related Questions