3

我對Android綁定服務有些疑惑。該指南:http://developer.android.com/guide/components/bound-services.html ,約bindService(),說:對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); 
} 

我錯了嗎?

+0

返回值有什麼意義恕我直言,例如,如果您的服務尚未運行,並綁定到它的標誌== 0返回值是true ,爲什麼?我不知道... – pskink 2014-09-30 18:05:09

+0

是的,這是矛盾的,因爲我們可以知道連接是否被創建,只有當onServiceConnect()被調用時,而不是立即。 – GVillani82 2014-09-30 18:08:22

+0

更糟糕的是:你的bindService()返回true,但是onServiceConnected()永遠不會被調用(當服務沒有啓動/創建並且標誌== 0時),我想你可以簡單地忘記返回的值並且只依賴於ServiceConnection – pskink 2014-09-30 18:12:24

回答

6

該文檔不正確。當返回的布爾值爲false時,這意味着不再進行建立連接的嘗試。當返回true時,這意味着系統嘗試建立連接,這可能成功或失敗。

看看這個問題的答案:"in what case does bindservice return false"。 基本上,bindservice在找不到服務甚至試圖綁定時返回false。

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