2

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

Kyle
  • 10,839
  • 17
  • 53
  • 63

1 Answers1

2

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
  • 13,020
  • 9
  • 37
  • 58
  • @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 Sep 02 '10 at 16:33
  • 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 Sep 02 '10 at 18:54