Android Binder機制(一)

binder用於android進程間的通訊。客戶端程序和系統服務,客戶端進程之間,都是通過binder進行進程間通訊的。

1.客戶端程序和系統服務

客戶端和系統服務通訊的入口:cotext.getSystemService(String name)

android.app.ContextImpl:

 
  1.  
  2.  
    public Object getSystemService(String name) {
  3.  
    return SystemServiceRegistry.getSystemService(this, name);
  4.  
    }

android.app.SystemServiceRegistry:

靜態代碼塊註冊系統服務:

 
  1.  
    static {
  2.  
    registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
  3.  
    new CachedServiceFetcher<AccessibilityManager>() {
  4.  
  5.  
    public AccessibilityManager createService(ContextImpl ctx) {
  6.  
    return AccessibilityManager.getInstance(ctx);
  7.  
    }});
  8.  
     
  9.  
    registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
  10.  
    new CachedServiceFetcher<CaptioningManager>() {
  11.  
  12.  
    public CaptioningManager createService(ContextImpl ctx) {
  13.  
    return new CaptioningManager(ctx);
  14.  
    }});
  15.  
     
  16.  
    registerService(Context.ACCOUNT_SERVICE, AccountManager.class,
  17.  
    new CachedServiceFetcher<AccountManager>() {
  18.  
  19.  
    public AccountManager createService(ContextImpl ctx) {
  20.  
    IBinder b = ServiceManager.getService(Context.ACCOUNT_SERVICE);
  21.  
    IAccountManager service = IAccountManager.Stub.asInterface(b);
  22.  
    return new AccountManager(ctx, service);
  23.  
    }});
  24.  
    ....

ServiceManager、ServiceManagerNative:

serviceManager是管理系統服務的一個工具類。

 
  1.  
    sServiceManager = ServiceManagerNative
  2.  
    .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));

getService方法:利用ServiceManagerProxy類通過進程間通訊的方式,獲取其他服務在binder驅動中的binder對象mRemote。

xxx.Stub.asInterface(binder):

利用getService獲取到的binder對象實例化相應服務的Proxy對象,返回給客戶端,供客戶端使用。

返回系統服務:

 
  1.  
    /**
  2.  
    * Gets a system service from a given context.
  3.  
    */
  4.  
    public static Object getSystemService(ContextImpl ctx, String name) {
  5.  
    ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
  6.  
    return fetcher != null ? fetcher.getService(ctx) : null;
  7.  
    }

2.客戶端之間

B應用進程調用A應用進程

B bindservice 向AmS請求啓動B應用的service。啓動service成功後會像AmS返回一個(binder驅動中的mRemote)binder,AmS會以該binder爲參數調用ActivityThread類中的ApplicatonThread對象。接着會在ApplicationThread中回調conn接口。最後,B進程可以利用該binder調用A應用提供的功能。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章