在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
一個實例)在ServiceConnection
的onServiceConnected()
方法中。 我的問題是,爲什麼我們試圖通過投作爲一個argument
到onServiceConnected()
的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;
}
};
...
}
「如果一個變量的類型在編譯時是已知的一門語言是靜態類型的。這實際上意味着,你作爲程序員必須指定每個變量是什麼類型」。 [參考](http://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages) - 現在我無法弄清楚這是如何相關的靜態打字。 – Solace 2014-10-22 00:05:57
@Zarah因爲鑄造。你不用動態語言(只是失敗)。當你演員表示你希望覆蓋編譯時可用的類型信息,因爲你知道的更好。你正在充滿活力。 – dcow 2014-10-22 00:33:59
非常感謝。 – Solace 2014-10-23 12:40:30