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应用提供的功能。

相关文章
相关标签/搜索