Android Binder機制(一)

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

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

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

android.app.ContextImpl:app

@Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }

android.app.SystemServiceRegistry:ide

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

static {
        registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
                new CachedServiceFetcher<AccessibilityManager>() {
            @Override
            public AccessibilityManager createService(ContextImpl ctx) {
                return AccessibilityManager.getInstance(ctx);
            }});

        registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
                new CachedServiceFetcher<CaptioningManager>() {
            @Override
            public CaptioningManager createService(ContextImpl ctx) {
                return new CaptioningManager(ctx);
            }});

        registerService(Context.ACCOUNT_SERVICE, AccountManager.class,
                new CachedServiceFetcher<AccountManager>() {
            @Override
            public AccountManager createService(ContextImpl ctx) {
                IBinder b = ServiceManager.getService(Context.ACCOUNT_SERVICE);
                IAccountManager service = IAccountManager.Stub.asInterface(b);
                return new AccountManager(ctx, service);
            }});
....

ServiceManager、ServiceManagerNative:fetch

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

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

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

xxx.Stub.asInterface(binder):code

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

返回系統服務:

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

2.客戶端之間

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

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

相關文章
相關標籤/搜索