//frameworks\native\libs\binder\IServiceManager.cpp
sp 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;
}
//frameworks\native\include\binder\IInterface.h
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);//相当于IServiceManager::asInterface(obj);
}
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
//相当于生成
const android::String16 IServiceManager::descriptor("android.os.IServiceManager"); \
const android::String16& IServiceManager::getInterfaceDescriptor() const {
return IServiceManager::descriptor;
}
android::sp<IServiceManager> IServiceManager::asInterface(
const android::sp<android::IBinder>& obj)
{
android::sp<IServiceManager> intr;
if (obj != NULL) {
intr = static_cast<IServiceManager*>(
obj->queryLocalInterface(
IServiceManager::descriptor).get());
if (intr == NULL) {
intr = new BpServiceManager(obj);
}
}
return intr;
}
IServiceManager::IServiceManager() { }
IServiceManager::~IServiceManager() { }
IServiceManager.asInterface();//等价于
new BpServiceManager(BpBinder);
//1. BpServiceManager具体实现
BpServiceManager(const sp<IBinder>& impl)
: BpInterface<IServiceManager>(impl) {}
//2、BpInterface初始化
BpInterface<IServiceManager>(impl);
//2.1 BpInterface具体实现
template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public:
BpInterface(const sp<IBinder>& remote);
protected:
virtual IBinder* onAsBinder();
};
BpRefBase::BpRefBase(const sp<IBinder>& o): mRemote(o.get()), mRefs(NULL), mState(0)
{
extendObjectLifetime(OBJECT_LIFETIME_WEAK);
if (mRemote) {
mRemote->incStrong(this); // Removed on first IncStrong().
mRefs = mRemote->createWeak(this); // Held for our entire lifetime.
}
}
//mRemote(o.get()) mRemote指向了new BpBinder(0)
//defaultServiceManager等价于new ServiceManager(new BpBinder(0));
//ProcessState.self()做了那些工作:
//1、调用open打开/dev/binder驱动设备
//2、再利用mmap,创建大小为1M-8k的内存空间
//3、设置当前进程最大并发Binder线程个数为8
//BpServiceManager巧妙的将通讯层与业务逻辑层融为一体
//通过继承接口IServiceManager实现了接口中的业务逻辑函数
//mRemote=new BpBinder(0)进行Binder通讯工作
//BpBinder通过handle来指向所对应得BBinder,在整个Binder系统中handle=0代表ServiceManager所对应得BBinder