binder用於android進程間的通訊。客戶端程序和系統服務,客戶端進程之間,都是通過binder進行進程間通訊的。
1.客戶端程序和系統服務
客戶端和系統服務通訊的入口:cotext.getSystemService(String name)
android.app.ContextImpl:
-
-
public Object getSystemService(String name) {
-
return SystemServiceRegistry.getSystemService(this, name);
-
}
android.app.SystemServiceRegistry:
靜態代碼塊註冊系統服務:
-
static {
-
registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
-
new CachedServiceFetcher<AccessibilityManager>() {
-
-
public AccessibilityManager createService(ContextImpl ctx) {
-
return AccessibilityManager.getInstance(ctx);
-
}});
-
-
registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
-
new CachedServiceFetcher<CaptioningManager>() {
-
-
public CaptioningManager createService(ContextImpl ctx) {
-
return new CaptioningManager(ctx);
-
}});
-
-
registerService(Context.ACCOUNT_SERVICE, AccountManager.class,
-
new CachedServiceFetcher<AccountManager>() {
-
-
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:
serviceManager是管理系統服務的一個工具類。
-
sServiceManager = ServiceManagerNative
-
.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
getService方法:利用ServiceManagerProxy類通過進程間通訊的方式,獲取其他服務在binder驅動中的binder對象mRemote。
xxx.Stub.asInterface(binder):
利用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應用提供的功能。