从SystemServer说起吧,SystemServer进程的名字实际上是system_server,是由Zygote进程创建的,SystemServer进程创建后会调用SystemServer.java中的main函数,main函数则调用native函数init1:
public static void main(String[] args)
{
...
init1(args);
}
函数init1的声明:
native public static void init1(String[] args);
其C++层的对应函数为com_android_server_SystemServer.cpp中的
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
system_init();
}
该函数调用system_init,位于System_init.cpp文件中:
extern "C" status_t system_init()
{
LOGI("Entered system_init()");
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm = defaultServiceManager();
LOGI("ServiceManager: %p\n", sm.get());
sp<GrimReaper> grim = new GrimReaper();
sm->asBinder()->linkToDeath(grim, grim.get(), 0);
//启动各个native services
char propBuf[PROPERTY_VALUE_MAX];
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0)
{
// Start the SurfaceFlinger
SurfaceFlinger::instantiate();
}
// Start the sensor service
SensorService::instantiate();
// On the simulator, audioflinger et al don't get started the
// same way as on the device, and we need to start them here
if (!proc->supportsProcesses())
{
// Start the AudioFlinger
AudioFlinger::instantiate();
// Start the media playback service
MediaPlayerService::instantiate();
// Start the camera service
CameraService::instantiate();
// Start the audio policy service
AudioPolicyService::instantiate();
}
// And now start the Android runtime. We have to do this bit
// of nastiness because the Android runtime initialization requires
// some of the core system services to already be started.
// All other servers should just start the Android runtime at
// the beginning of their processes's main(), before calling
// the init function.
LOGI("System server: starting Android runtime.\n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
//回调SystemServer中的init2函数,启动android services
LOGI("System server: starting Android services.\n");
runtime->callStatic("com/android/server/SystemServer", "init2");
// If running in our own process, just go into the thread
// pool. Otherwise, call the initialization finished
// func to let this process continue its initilization.
if (proc->supportsProcesses())
{
LOGI("System server: entering thread pool.\n");
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
LOGI("System server: exiting thread pool.\n");
}
return NO_ERROR;
}
public static final void init2()
{
Slog.i(TAG, "Entered the Android system server!");
Thread thr = new ServerThread();
thr.setName("android.server.ServerThread");
thr.start();
}
在init2函数中启动一个ServerThread线程,在该线程的run函数中会创建一系列的Android Services:
// Critical services...
try {
Slog.i(TAG, "Entropy Service");
ServiceManager.addService("entropy", new EntropyService());
Slog.i(TAG, "Power Manager");
power = new PowerManagerService();
ServiceManager.addService(Context.POWER_SERVICE, power);
Slog.i(TAG, "Activity Manager");
context = ActivityManagerService.main(factoryTest);
if(SystemProperties.getBoolean("hw.hasdata", true)) {
Slog.i(TAG, "Telephony Registry");
ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));
}
AttributeCache.init(context);
Slog.i(TAG, "Package Manager");
pm = PackageManagerService.main(context,
factoryTest != SystemServer.FACTORY_TEST_OFF);
ActivityManagerService.setSystemProcess();
mContentResolver = context.getContentResolver();
// The AccountManager must come before the ContentService
try {
Slog.i(TAG, "Account Manager");
ServiceManager.addService(Context.ACCOUNT_SERVICE,
new AccountManagerService(context));
} catch (Throwable e) {
Slog.e(TAG, "Failure starting Account Manager", e);
}
Slog.i(TAG, "Content Manager");
ContentService.main(context,
factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();
Slog.i(TAG, "Battery Service");
battery = new BatteryService(context);
ServiceManager.addService("battery", battery);
Slog.i(TAG, "Lights Service");
lights = new LightsService(context);
Slog.i(TAG, "Vibrator Service");
ServiceManager.addService("vibrator", new VibratorService(context));
// only initialize the power service after we have started the
// lights service, content providers and the battery service.
power.init(context, lights, ActivityManagerService.getDefault(), battery);
Slog.i(TAG, "Alarm Manager");
AlarmManagerService alarm = new AlarmManagerService(context);
ServiceManager.addService(Context.ALARM_SERVICE, alarm);
Slog.i(TAG, "Init Watchdog");
Watchdog.getInstance().init(context, battery, power, alarm,
ActivityManagerService.self());
Slog.i(TAG, "Window Manager");
wm = WindowManagerService.main(context, power,
factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
((ActivityManagerService)ServiceManager.getService("activity"))
.setWindowManager(wm);
...
自然也包含WindowManagerService Service:
wm = WindowManagerService.main(context, power,
factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
调用WindowManagerService类的main函数:
public static WindowManagerService main(Context context,
PowerManagerService pm, boolean haveInputMethods)
{
WMThread thr = new WMThread(context, pm, haveInputMethods);
thr.start();
synchronized (thr)
{
while (thr.mService == null)
{
try
{
thr.wait();
}
catch (InterruptedException e)
{
}
}
}
return thr.mService;
}
创建一个WMThread 线程对象并执行,在其run函数中:
public void run()
{
Looper.prepare();
WindowManagerService s = new WindowManagerService(mContext, mPM,
mHaveInputMethods);
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_DISPLAY);
android.os.Process.setCanSelfBackground(false);
synchronized (this) {
mService = s;
notifyAll();
}
Looper.loop();
}
调用WindowManagerService的构造函数,其构造函数是private的(WindowManagerService有且只有一个private的构造函数),并且创建Looper来处理消息,private的WindowManagerService构造函数中做的事情也很多,此处我们关注的是Android的输入,则:
mInputManager = new InputManager(context, this);
mInputManager.start();
此处InputManager并非是Thread的子类,因此调用start并不会创建一个新的线程,InputManager.java中关于InputManager类有如下说明:
Wraps the C++ InputManager and provides its callbacks.
即其作用是负责Java层包装底层的C++函数并且为这些C++函数提供Java层的回调函数,InputManager.java中有大量的native函数,可以证实InputManager.java中的InputManager负担的Java层与C++层之间沟通的功能,
InputManager.java中InputManager类的构造函数如下:
public InputManager(Context context, WindowManagerService windowManagerService)
{
this.mContext = context;
this.mWindowManagerService = windowManagerService;
this.mCallbacks = new Callbacks();
init();
}
调用了InputManager.java中的init函数,此函数不是native函数,但是其调用了native函数:
private void init()
{
Slog.i(TAG, "Initializing input manager");
nativeInit(mCallbacks);
}
private static native void nativeInit(Callbacks callbacks);
其C++层的对应函数为com_android_server_InputManager.cpp中的
{ "nativeInit", "(Lcom/android/server/InputManager$Callbacks;)V",
(void*) android_server_InputManager_nativeInit },
static void android_server_InputManager_nativeInit(JNIEnv* env, jclass clazz,
jobject callbacks)
{
printf("android_server_InputManager_nativeInit, create NativeInputManager\n");
if (gNativeInputManager == NULL)
{
gNativeInputManager = new NativeInputManager(callbacks);
}
else
{
LOGE("Input manager already initialized.");
jniThrowRuntimeException(env, "Input manager already initialized.");
}
}
在该函数中gNativeInputManager = new NativeInputManager(callbacks);
而NativeInputManager的构造函数中:
NativeInputManager::NativeInputManager(jobject callbacksObj) :
mFilterTouchEvents(-1), mFilterJumpyTouchEvents(-1), mVirtualKeyQuietTime(-1),
mMaxEventsPerSecond(-1),
mDisplayWidth(-1), mDisplayHeight(-1), mDisplayOrientation(ROTATION_0)
{
JNIEnv* env = jniEnv();
mCallbacksObj = env->NewGlobalRef(callbacksObj);
sp<EventHub> eventHub = new EventHub();
mInputManager = new InputManager(eventHub, this, this);
}
创建了EventHub对象和InputManager对象
EventHub的构造函数,似乎没有做太多的事情:
EventHub::EventHub(void)
: mError(NO_INIT)
, mHaveFirstKeyboard(false)
, mFirstKeyboardId(0)
, mDevicesById(0)
, mNumDevicesById(0)
, mOpeningDevices(0)
, mClosingDevices(0)
, mDevices(0)
, mFDs(0)
, mFDCount(0)
, mOpened(false)
, mNeedToSendFinishedDeviceScan(false)
, mInputBufferIndex(0)
, mInputBufferCount(0)
, mInputDeviceIndex(0)
#ifdef HAVE_TSLIB
, mTS()
#endif
{
acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
#ifdef EV_SW
memset(mSwitches, 0, sizeof(mSwitches));
#endif
}
而InputManager构造函数中:
InputManager::InputManager(
const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& readerPolicy,
const sp<InputDispatcherPolicyInterface>& dispatcherPolicy)
{
mDispatcher = new InputDispatcher(dispatcherPolicy);
mReader = new InputReader(eventHub, readerPolicy, mDispatcher);
initialize();
}
InputManager的构造函数中做了比较多的事情,创建了InputDispatcher,InputReader的对象,
并且initialize函数中:
void InputManager::initialize()
{
mReaderThread = new InputReaderThread(mReader);
mDispatcherThread = new InputDispatcherThread(mDispatcher);
}
创建了各个线程:
InputReaderThread负责:Reads raw events from the event hub and processes them, endlessly.
InputDispatcherThread负责:/* Enqueues and dispatches input events, endlessly. */
创建这些线程后,并未立即运行。
InputManager.java中的start函数:
public void start() {
Slog.i(TAG, "Starting input manager");
nativeStart();
}
调用nativeStart函数,nativeStart函数是native的,对应于com_android_server_InputManager.cpp中的
{ "nativeStart", "()V",
(void*) android_server_InputManager_nativeStart },
即android_server_InputManager_nativeStart函数:
static void android_server_InputManager_nativeStart(JNIEnv* env, jclass clazz)
{
...
status_t result = gNativeInputManager->getInputManager()->start();
...
}
gNativeInputManager是static sp<NativeInputManager> gNativeInputManager;
getInputManager:
inline sp<InputManager> getInputManager() const { return mInputManager; }
而mInputManager是sp<InputManager> mInputManager;
因此start函数则是InputManager中的start函数:
status_t InputManager::start()
{
status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
if (result) {
LOGE("Could not start InputDispatcher thread due to error %d.", result);
return result;
}
result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);
if (result) {
LOGE("Could not start InputReader thread due to error %d.", result);
mDispatcherThread->requestExit();
return result;
}
return OK;
}
在这个函数中分别启动之前创建的mReaderThread和mDispatcherThread线程。
后续的问题:
1、EventHub构造时的详细过程,设备的管理?
2、EventHub、InputReader、InputDispatcher三者之间的关系,如何形成从底层读取事件、分发事件这样完整的循环?