class BpServiceManager : public BpInterface { public:
BpServiceManager(const sp& impl) : BpInterface(impl) { } ...
virtual status_t addService(const String16& name, const sp& service) {
Parcel data, reply;
data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); data.writeString16(name); data.writeStrongBinder(service);
status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply); return err == NO_ERROR ? reply.readInt32() : err; } ... };
BpServiceManager实现了 IServiceManager和IBinder两个接口,调用者可以把BpServiceManager的对象看作是一个IServiceManager对象或者IBinder对象。当调用者把BpServiceManager对象当作IServiceManager对象使用时,所有的请求只是对
BpBinder::transact的封装。这样的封装使得调用者不需要关心IServiceManager对象是本地的还是远程的了。
客户通过defaultServiceManager函数来创建BpServiceManager对象: (frameworks/base/libs/utils/IServiceManager.cpp)
sp
if (gDefaultServiceManager != NULL) return gDefaultServiceManager; {
AutoMutex _l(gDefaultServiceManagerLock); if (gDefaultServiceManager == NULL) {
gDefaultServiceManager = interface_cast
return gDefaultServiceManager; }
先通过ProcessState::self()->getContextObject(NULL)创建一个Binder对象,然后通过interface_cast和IMPLEMENT_META_INTERFACE(ServiceManager,
“android.os.IServiceManager”)把Binder对象包装成 IServiceManager对象。原理上等同于创建了一个BpServiceManager对象。
ProcessState::self()->getContextObject调用ProcessState::getStrongProxyForHandle创建代理对象:
sp
sp
AutoMutex _l(mLock);
handle_entry* e = lookupHandleLocked(handle);
if (e != NULL) {
// We need to create a new BpBinder if there isn't currently one, OR we
// are unable to acquire a weak reference on this current one. See comment // in getWeakProxyForHandle() for more info about this. IBinder* b = e->binder;
if (b == NULL || !e->refs->attemptIncWeak(this)) { b = new BpBinder(handle); e->binder = b;
if (b) e->refs = b->getWeakRefs(); result = b; } else {
// This little bit of nastyness is to allow us to add a primary // reference to the remote proxy when this team doesn't have one // but another team is sending the handle to us. result.force_set(b); e->refs->decWeak(this); } }
return result; }
如果handle为空,默认为context_manager对象,context_manager实际上就是ServiceManager。 o 服务端
服务端也要实现IBinder接口,BBinder类对IBinder接口提供了部分默认实现,其中transact的实现如下:
status_t BBinder::transact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
data.setDataPosition(0);
status_t err = NO_ERROR; switch (code) {
case PING_TRANSACTION: reply->writeInt32(pingBinder()); break; default:
err = onTransact(code, data, reply, flags); break; }
if (reply != NULL) {
reply->setDataPosition(0); }
return err; }
PING_TRANSACTION请求用来检查对象是否还存在,这里简单的把 pingBinder的返回值返回给调用者。其它的请求交给onTransact处理。onTransact是BBinder里声明的一个protected类型的虚函数,这个要求它的子类去实现。比如CameraService里的实现如下:
status_t CameraService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
// permission checks... switch (code) {
case BnCameraService::CONNECT:
IPCThreadState* ipc = IPCThreadState::self();
相关推荐: