开发者

bindService not working inside a button click but works in onCreate - android

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 ou开发者_如何学编程t 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜