首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对bindService的质疑

对bindService的质疑
EN

Stack Overflow用户
提问于 2014-09-30 17:58:48
回答 2查看 1.4K关注 0票数 3

我有一些关于Android绑定服务的细节。指南:http://developer.android.com/guide/components/bound-services.html,关于bindService(),说:

代码语言:javascript
复制
The `bindService()` method returns immediately without a value

但是这似乎不正确,因为这里方法的签名是

代码语言:javascript
复制
public abstract boolean bindService (Intent service, ServiceConnection conn, int flags)

其中返回的布尔值描述如下:

代码语言:javascript
复制
If you have successfully bound to the service, true is returned; false is returned if the connection is not made so you will not receive the service object.

所以问题是:为什么文档说方法是returns immediately without a value?此外,在这里中,绑定是以这种方式完成的:

代码语言:javascript
复制
void doBindService() {
    bindService(new Intent(Binding.this, 
            LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

我不明白mIsBound = true的含义,因为javadoc说,如果服务边界失败,bindService()也可以返回false。所以应该是:

代码语言:javascript
复制
void doBindService() {
    mIsBound = bindService(new Intent(Binding.this, 
            LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
}

我说错了吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-30 18:30:39

文件不正确。当返回的布尔值为false时,这意味着不再进行建立连接的尝试。当返回true时,这意味着系统试图建立连接,这可以成功,也可以失败。

看看这个问题的答案:“在何种情况下,bindservice返回false”。基本上,当绑定服务找不到要绑定到的服务时,它会返回false。

票数 6
EN

Stack Overflow用户

发布于 2016-01-04 23:06:45

好的,我终于学会了android中绑定服务的所有细微之处,这就是ServiceBindHelper类,它可以被看作是“终极真理”(请原谅我的不谦虚)。

https://gist.github.com/attacco/987c55556a2275f62a16

用法示例:

代码语言:javascript
复制
class MyActivity extends Activity {
    private ServiceBindHelper<MyService> myServiceHelper;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myServiceHelper = new ServiceBindHelper<MyService>(this) {
            @Override
            protected Intent createBindIntent() {
                return new Intent(MyActivity.this, MyService.class);
            }

            @Override
            protected MyService onServiceConnected(ComponentName name, IBinder service) {
                // assume, that MyService is just a simple local service
                return (MyService) service;
            }
        };
        myServiceHelper.bind();
    }

    protected void onDestroy() {
        super.onDestroy();
        myServiceHelper.unbind();
    }

    protected void onStart() {
        super.onStart();
        if (myServiceHelper.getService() != null) {
            myServiceHelper.getService().doSmth();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26127129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档