views:

27

answers:

1

I have a pretty simple local service that I'm trying to bind to my activity. I worked through this yesterday with CommonsWare and he got me straightened out as I was having a difficult time getting the service to bind. It turns out that the reason I was having so much trouble was that I was trying to bind the service with:

bindService(new Intent(this, myService.class), mConnection, Context.BIND_AUTO_CREATE);

inside a void method that was being called after a button click.

private void doBindService() {
            bindService(new Intent(this, SimpleService.class), mConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
        }

       private OnClickListener startListener = new OnClickListener() {
        public void onClick(View v){
            doBindService();
        }               
       };

when I moved my bindService() call to the onCreate method of the activity, it works fine. CommonsWare mentioned something about that call being asynchronous and I don't know enough about android activity creation to know if that's what my issue was or not. I do know that my onServiceConnection() was being called inside my ServiceConnection() when the button was being clicked, by my mBoundService would not work when I tried accessing members inside the service.

Can someone tell me why it doesn't work inside the button click, but does work inside the onCreate()?

TIA

+1  A: 

The this reference inside of doBindService is not the same in both instances. If called in onCreate it will be a reference to the Activity if called from the button click it will be a reference to the OnClickListener. Obviously you do not want your service bound to the buttons click listener.

Try changing this to YOURACTIVITYNAME.this and see if that helps.

smith324
@chris324 - thanks for the reply, but if you look more carefully, the bindService() gets called from a void method that's part of the activity class which is called from the click. So for all intents and purposes, 'this' would refer to the activity would it not?
Kyle
No, it doesn't matter where the function is defined. It's called from a different class and thus the `this` will point to that
Falmarri
ok thanks....I didn't know that :/
Kyle