android的系统服务是由SystemServer.java开始的。zygote进程启动了SystemServer进程。SystemServer类中有静态main函数,SystemServer进程就是从这里开始的。
在SystemServer类的main函数中会new ServerThread类,该类时SystemServer的内部类。main函数中会执行ServerThread对象的initAndLoop()方法。
在initAndLoop()方法中,会首先启动一个Looper,然后获取到ServiceManager,接着用ServiceManager的addService方法,将所有的系统Service都增加到ServiceManagerNative类中。其中ServiceManager类是提供给用户的接口,ServiceManagerNative是它的具体实现。
接着我们看ServiceManagerNative类中addService方法的源代码:
public void addService(String name, IBinder service, boolean allowIsolated)
throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IServiceManager.descriptor);
data.writeString(name);
data.writeStrongBinder(service);
data.writeInt(allowIsolated ? 1 : 0);
mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
reply.recycle();
data.recycle();
}
我们看到会将某个系统Service发送到mRemote中,而这个mRemote是什么呢?这个mRemote是BinderInternal的getContextObject方法获取到的IBinder对象。getContextObject这个方法是native的,也就是说各个系统Service是由SystemServer进程的native代码来管理的。
public static final native IBinder getContextObject();
在《Android内核剖析》这本书中看到一幅进程图,摘录如下: