Doubts about bindService

人盡茶涼 提交于 2019-12-01 20:33:40
Okas

The documentation is incorrect. When returned boolean is false this means that no further attempts to establish connection are made. When true is returned this means that system tries to establish a connection and this can succeed or fail.

Look at answer for this question: "in what case does bindservice return false". Basically bindservice returns false when it does not find a service to even attempt to bind to.

Ok, i finally completed learning all the nuances of binding services in android, and that is the ServiceBindHelper class, that can be treated as "ultimate truth" (excuse my immodesty).

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

Usage example:

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();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!