Android 輸入法框架涉及 InputMethodManager、InputMethodManagerService、InputMethodService 與多個 Binder 介面。理解這些元件之間的呼叫關係,有助於掌握輸入法如何與應用程式溝通。
InputMethodManager 是應用層存取輸入法的主要入口。它內部持有 IInputMethodSession,並透過 IInputMethodClient.Stub 接收 InputMethodManagerService 的回呼。當收到 MSG_BIND 時,會把 InputBindResult 中的 method 指派給 mCurMethod。
InputMethodManagerService 在建立 session 後,會透過 MSG_BIND_METHOD 呼叫用戶端的 onBindMethod。這個訊息通常由 onSessionCreated 觸發,而 onSessionCreated 又是在輸入法服務建立 session 後回呼。
InputMethodManagerService 中的 mCurMethod 並非凭空產生,而是在 onServiceConnected 中,透過 InputMethodService 提供的 Binder 取得。InputMethodService 繼承自 AbstractInputMethodService,而後者在 onBind 中會回傳 IInputMethodWrapper。
當需要建立 session 時,InputMethodManagerService 會發送 MSG_CREATE_SESSION。IInputMethodWrapper 收到後,會呼叫 InputMethod 的 createSession。AbstractInputMethodImpl 的 createSession 會回呼 MethodCallback.sessionCreated,並把 InputMethodSession 傳回服務端。
最終可以整理為:InputMethodManager 透過 InputMethodManagerService 的本地代理存取系統服務;InputMethodManager 透過 IInputMethodSession 與 InputMethodService 互動;InputMethodManagerService 透過 IInputMethodClient 回呼 InputMethodManager;並透過 IInputMethodWrapper 回呼 InputMethodService。