上一节分析了 InputManagerService 初始化,这一节重点关注启动以后都做了一些什么?
frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
......
public static void main(String[] args) {
new SystemServer().run();
}
......
private void run() {
......
try {
......
startOtherServices();
} catch (Throwable ex) {
......
}
......
}
......
private void startOtherServices() {
......
WindowManagerService wm = null;
......
InputManagerService inputManager = null;
......
try {
......
// 启动 InputManagerService
inputManager.start();
......
} catch (RuntimeException e) {
......
}
}
......
}
InputManagerService start 方法完成了 InputManagerService 启动。把获取到的输入事件进行处理,最后分发给对应的处理窗口,或者拦截到相应处理过程中进行处理。nativeStart 从方法名可知是做一些 native 启动工作的, mPtr 是指向 native input manager 服务对象的指针。
frameworks/base/services/core/java/com/android/server/input/InputManagerService.java
public class InputManagerService extends IInputManager.Stub
implements Watchdog.Monitor {
......
public void start() {
Slog.i(TAG, "Starting input manager");
// mPtr 是指向 native input manager 服务对象的指针
nativeStart(mPtr);
// 添加到看门狗监视器
Watchdog.getInstance().addMonitor(this);
......
}
......
}
首先将传递过来的 jlong 转化为 NativeInputManager 指针,接着调用其 getInputManager() 获取 InputManager 对象,最后调用 InputManager 的 start 方法。
frameworks/base/services/core/jni/com_android_server_input_InputManagerService.cpp
static void nativeStart(JNIEnv* env, jclass /* clazz */, jlong ptr) {
NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
status_t result = im->getInputManager()->start();
if (result) {
jniThrowRuntimeException(env, "Input manager could not be started.");
}
}
getInputManager 函数是一个内联函数。
frameworks/base/services/core/jni/com_android_server_input_InputManagerService.cpp
class NativeInputManager : public virtual RefBase,
public virtual InputReaderPolicyInterface,
public virtual InputDispatcherPolicyInterface,
public virtual PointerControllerPolicyInterface {
......
public:
......
inline sp<InputManager> getInputManager() const { return mInputManager; }
......
private:
sp<InputManager> mInputManager;
......
};
1.启动 DispatcherThread;
2.启动 ReaderThread。
frameworks/native/services/inputflinger/InputManager.cpp
status_t InputManager::start() {
// 1.启动 DispatcherThread
status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
if (result) {
ALOGE("Could not start InputDispatcher thread due to error %d.", result);
return result;
}
// 2.启动 ReaderThread
result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);
if (result) {
ALOGE("Could not start InputReader thread due to error %d.", result);
// 请求退出 DispatcherThread
mDispatcherThread->requestExit();
return result;
}
return OK;
}
到了这一步, InputManagerService 就跑起来了,InputReaderThread 负责读取输入事件,InputDispatcherThread 负责派发事件到当前窗口进行处理。如果 InputReaderThread 启动失败,则调用 InputDispatcherThread requestExit 方法请求退出派发事件线程。