怀疑bindService

时间:2014-09-30 17:58:48

标签: android android-activity android-service android-service-binding

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

The `bindService()` method returns immediately without a value

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

public abstract boolean bindService (Intent service, ServiceConnection conn, int flags)

返回的布尔值如下所示:

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?而且,here,绑定以这种方式完成:

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

并且我不理解mIsBound = true的意义,因为javadoc说如果绑定到服务失败,bindService()也可以返回false。所以它应该是:

void doBindService() {
    mIsBound = bindService(new Intent(Binding.this, 
            LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
}

我错了吗?

2 个答案:

答案 0 :(得分:6)

文档不正确。当返回boolean为false时,这意味着不再进行建立连接的尝试。当返回true时,这意味着系统尝试建立连接,这可能成功或失败。

看看这个问题的答案:"in what case does bindservice return false"。 基本上,bindservice在找不到甚至尝试绑定的服务时返回false。

答案 1 :(得分:0)

好的,我终于完成了学习android中绑定服务的所有细微差别,那就是ServiceBindHelper类,可以被视为“终极真理”(原谅我的不诚实)。

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

用法示例:

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();
        }
    }
}