前面讲了里面binder的接口,怎么将service注册到系统,以及service的接口是怎么调用的,接下来要分析client端怎么拿到binder proxy和调用到service端去。
1、和cameraservice进程进行binder通信,首先要拿到它的proxy对象,代码如下
sp<IServiceManager> sm = defaultServiceManager(); //servicemanger 的proxy
sp<IBinder> binder;
do {
binder = sm->getService(String16(kCameraServiceName)); //通过service name从servicemanager拿到service 的proxy
if (binder != 0) {
break;
}
ALOGW("CameraService not published, waiting...");
usleep(kCameraServicePollDelay);
} while(true);
gCameraService = interface_cast<::android::hardware::ICameraService>(binder);
1)defaultServiceManager()
sp<IServiceManager> defaultServiceManager()
{
if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
{
AutoMutex _l(gDefaultServiceManagerLock);
while (gDefaultServiceManager == NULL) {
gDefaultServiceManager = interface_cast<IServiceManager>(
ProcessState::self()->getContextObject(NULL));
if (gDefaultServiceManager == NULL)
sleep(1);
}
}
return gDefaultServiceManager;
}
2)ProcessState 和 IPCThreadState前面已经介绍过了
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
{
return getStrongProxyForHandle(0);
}
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result;
AutoMutex _l(mLock);
handle_entry* e = lookupHandleLocked(handle);
if (e != NULL) {
IBinder* b = e->binder;
if (b == NULL || !e->refs->attemptIncWeak(this)) {
if (handle == 0) {
// Special case for context manager...
// The context manager is the only object for which we create
// a BpBinder proxy without already holding a reference.
// Perform a dummy transaction to ensure the context manager
// is registered before we create the first local reference
// to it (which will occur when creating the BpBinder).
// If a local reference is created for the BpBinder when the
// context manager is not present, the driver will fail to