0

developer docs for Bound Services,下面的代碼示例在「創建綁定的服務」給予「擴展類粘合劑」。下面的代碼段(我已刪除不相關比特)給出其中Service從其onBind()方法的IBinder返回:Android綁定服務:爲什麼我們將此IBinder實例放入IBinder實例中?

public class LocalService extends Service { 
    // Binder given to clients 
    private final IBinder mBinder = new LocalBinder(); 
    ... 
    /** 
    * Class used for the client Binder. Because we know this service always 
    * runs in the same process as its clients, we don't need to deal with IPC. 
    */ 
    public class LocalBinder extends Binder { 
     LocalService getService() { 
      // Return this instance of LocalService so clients can call public methods 
      return LocalService.this; 
     } 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return mBinder; //********************************************************** 
    } 
    ... 
} 

然後,在我們的客戶端,我們得到的mBinder對象(這是LocalBinder一個實例)在ServiceConnectiononServiceConnected()方法中。 我的問題是,爲什麼我們試圖通過投作爲一個argumentonServiceConnected()LocalBinder一個實例爲LocalBinder實例在聲明中LocalBinder binder = (LocalBinder) service;

public class BindingActivity extends Activity { 
    LocalService mService; 
    boolean mBound = false; 
    ... 

    /** Defines callbacks for service binding, passed to bindService() */ 
    private ServiceConnection mConnection = new ServiceConnection() { 

     @Override 
     public void onServiceConnected(ComponentName className, 
       IBinder service) { 
      // We've bound to LocalService, cast the IBinder and get LocalService instance 
      LocalBinder binder = (LocalBinder) service; 
      mService = binder.getService(); 
      mBound = true; 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName arg0) { 
      mBound = false; 
     } 
    }; 
    ... 
} 

回答

3

ServiceConnection.onServiceConnected()定義是

公共無效onServiceConnected(組件名稱的className,的IBinder服務)

注意,參數是IBinder - ServiceConnection不知道什麼樣的服務或什麼樣的IBinder實現服務返回 - 只有你知道,因此你需要將它轉換爲正確的類型。

2

因爲你在有唯一的類型信息onServiceConnected是,你IBinder類型的對象。 IBinder都不具備的一個的getService方法,所以你必須執行IBinder對象強制轉換爲LocalBinder類型的對象。然後您可以撥打getService方法。這就是靜態類型的工作原理。

+0

「如果一個變量的類型在編譯時是已知的一門語言是靜態類型的。這實際上意味着,你作爲程序員必須指定每個變量是什麼類型」。 [參考](http://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages) - 現在我無法弄清楚這是如何相關的靜態打字。 – Solace 2014-10-22 00:05:57

+1

@Zarah因爲鑄造。你不用動態語言(只是失敗)。當你演員表示你希望覆蓋編譯時可用的類型信息,因爲你知道的更好。你正在充滿活力。 – dcow 2014-10-22 00:33:59

+0

非常感謝。 – Solace 2014-10-23 12:40:30