bindService 不在按钮单击内工作,但在 onCreate 中工作 - android
我有一个非常简单的本地服务,我试图将其绑定到我的活动。昨天我与 CommonsWare 一起解决了这个问题,他让我理清了思路,因为我在绑定服务时遇到了困难。事实证明,我遇到这么多麻烦的原因是我试图将服务绑定到:
bindService(new Intent(this, myService.class), mConnection, Context.BIND_AUTO_CREATE);
在单击按钮后调用的 void 方法内。
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();
}
};
当我将 bindService() 调用移至活动的 onCreate 方法时,它工作正常。 CommonsWare 提到了一些关于该调用是异步的,我对 android 活动创建了解不够,不知道这是否是我的问题。我确实知道,当单击按钮时,我的 onServiceConnection() 在 ServiceConnection() 内部被调用,当我尝试访问服务内的成员时,我的 mBoundService 将无法工作。
有人能告诉我为什么它在按钮单击内不起作用,但在 onCreate() 内起作用吗?
TIA
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在两个实例中,
doBindService
内部的this
引用并不相同。如果在onCreate
中调用,它将是对Activity
的引用,如果从按钮单击调用,它将是对OnClickListener
的引用。显然您不希望您的服务绑定到按钮单击侦听器。尝试将
this
更改为YOURACTIVITYNAME.this
并查看是否有帮助。The
this
reference inside ofdoBindService
is not the same in both instances. If called inonCreate
it will be a reference to theActivity
if called from the button click it will be a reference to theOnClickListener
. Obviously you do not want your service bound to the buttons click listener.Try changing
this
toYOURACTIVITYNAME.this
and see if that helps.