按键事件

对于按键事件,调用mDevices->layoutMap->map进行映射。映射实际是由 KeyLayoutMap::map完成的,KeyLayoutMap类里读取配置文件qwerty.kl ,由配置 文件 qwerty.kl 决定键值的映射关系。你可以通过修 改./development/emulator/keymaps/qwerty.kl来改变键值的映射关系。 

JNI 函数 
在 frameworks/base/services/jni /com_android_server_KeyInputQueue.cpp文 件中,向 JAVA提供了函数android_server_KeyInputQueue_readEvent,用于读 取输入设备事件 。 
C代码: 

 
static jboolean android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz, 
                                           jobject event)

    gLock.lock(); 
    sp hub = gHub; 
    if (hub == NULL) { 
        hub = new EventHub; 
        gHub = hub; 
    } 
    gLock.unlock(); 
    int32_t deviceId; 
    int32_t type; 
    int32_t scancode, keycode; 
    uint32_t flags; 
    int32_t value; 
    nsecs_t when; 
    bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode, 
            &flags, &value, &when); 
    env->SetIntField(event, gInputOffsets.mDeviceId, (jint)deviceId); 
    env->SetIntField(event, gInputOffsets.mType, (jint)type); 
    env->SetIntField(event, gInputOffsets.mScancode, (jint)scancode); 
    env->SetIntField(event, gInputOffsets.mKeycode, (jint)keycode); 
    env->SetIntField(event, gInputOffsets.mFlags, (jint)flags); 
    env->SetIntField(event, gInputOffsets.mValue, value); 
    env->SetLongField(event, gInputOffsets.mWhen, 
                       (jlong)(nanoseconds_to_milliseconds(when))); 
    return res; 
}

 readEvent调用hub->getEvent读了取事件,然后转换成JAVA的结构 。 

事件中转线程 
在frameworks/base/services/java /com/android/server/KeyInputQueue.java 里创建了一个线程,它循环的读取事件,然后把事件放入事件队列里。 
Java代码:·

 

Thread mThread = new Thread("InputDeviceReader") {
        public void run() {
            android.os.Process.setThreadPriority(
                    android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
            
            try {
                RawInputEvent ev = new RawInputEvent();
                while (true) {
                    InputDevice di;

                    // block, doesn't release the monitor
                    readEvent(ev);

                    boolean send = false;
                    boolean configChanged = false;
                    
                    if (false) {
                        Log.i(TAG, "Input event: dev=0x"
                                + Integer.toHexString(ev.deviceId)
                                + " type=0x" + Integer.toHexString(ev.type)
                                + " scancode=" + ev.scancode
                                + " keycode=" + ev.keycode
                                + " value=" + ev.value);
                    }
                    
                    if (ev.type == RawInputEvent.EV_DEVICE_ADDED) {
                        synchronized (mFirst) {
                            di = newInputDevice(ev.deviceId);
                            mDevices.put(ev.deviceId, di);
                            configChanged = true;
                        }
                    }

            ......
          }
        }
      }
};

按键、触摸屏流、轨迹球程分析

输入事件分发线程 
在frameworks/base/services/java/com/android/server/WindowManagerService.java里创建了一个输入事件分发线程,它负责把事件分发到相应的窗口上去。


按键触摸屏流程分析: 

    WindowManagerService类的构造函数

    WindowManagerService()

    mQueue = new KeyQ(); 

因为 WindowManagerService.java (frameworks\base\services\java\com\android\server)中有:

private class KeyQ extends KeyInputQueue implements KeyInputQueue.FilterCallback

KeyQ 是抽象类 KeyInputQueue 的实现,所以 new KeyQ类的时候实际上在 KeyInputQueue 类中创建了一个线程 InputDeviceReader 专门用来从设备读取按键事件,

代码: 

Thread mThread = new Thread("InputDeviceReader") { 

    public void run() { 

        // 在循环中调用:
     readEvent(ev); 
        ... 
        send = preprocessEvent(di, ev); 
  
        //实际调用的是 KeyQ 类的 preprocessEvent 函数 
         ... 
        int keycode = rotateKeyCodeLocked(ev.keycode); 
 
        int[] map = mKeyRotationMap; 

        for (int i=0; i<N; i+=2) { 

            if (map == keyCode)  

            return map[i+1]; 

        } // 

        addLocked(di, curTime, ev.flags,RawInputEvent.CLASS_KEYBOARD,
                  newKeyEvent(di, di.mDownTime, curTime, down,keycode, 0, scancode,...)); 

        QueuedEvent ev = obtainLocked(device, when, flags, classType, event); 
    } 
}; 

readEvent() 实际上调用的是 com_android_server_KeyInputQueue.cpp (frameworks\base\services\jni)中的

static jboolean android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz,jobject event) 来读取事件,

 

bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode,&flags, &value, &when)调用的是EventHub.cpp (frameworks\base\libs\ui)中的: 

    bool EventHub::getEvent (int32_t* outDeviceId, int32_t* outType, 

            int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags, 

            int32_t* outValue, nsecs_t* outWhen) 

在函数中调用了读设备操作:res = read(mFDs.fd, &iev, sizeof(iev)); 

在构造函数 WindowManagerService()调用 new KeyQ() 以后接着调用了: 

    mInputThread = new InputDispatcherThread();       
    ...     

    mInputThread.start(); 

来启动一个线程 InputDispatcherThread 

    run() 
    process(); 
    QueuedEvent ev = mQueue.getEvent(...) 

因为WindowManagerService类中: final KeyQ mQueue; 

所以实际上 InputDispatcherThread 线程实际上从 KeyQ 的事件队列中读取按键事件,在process() 方法中进行处理事件。

    switch (ev.classType) 
    case RawInputEvent.CLASS_KEYBOARD: 
        ... 
        dispatchKey((KeyEvent)ev.event, 0, 0); 
        mQueue.recycleEvent(ev); 
        break; 
    case RawInputEvent.CLASS_TOUCHSCREEN: 
        //Log.i(TAG, "Read next event " + ev); 
        dispatchPointer(ev, (MotionEvent)ev.event, 0, 0); 
        break;

  case RawInputEvent.CLASS_TRACKBALL:
        dispatchTrackball(ev, (MotionEvent)ev.event, 0, 0);
        break;

 

===============================================================

补充一些内容:

在写程序时,需要捕获KEYCODE_HOME、KEYCODE_ENDCALL、KEYCODE_POWER这几个按键,但是这几个按键系统做了特殊处理,在进行dispatch之前做了一些操作,HOME除了Keygaurd之外,不分发给任何其他 APP,ENDCALL和POWER也类似,所以需要我们系统处理之前进行处理。

我的做法是自己定义一个FLAG,在自己的程序中添加此FLAG,然后在WindowManagerServices.java中获取当前窗口的FLAG属性,如果是我们自己设置的那个FLAG,则不进行特殊处理,直接分发按键消息到我们的APP当中,由APP自己处理。

这部分代码最好添加在

@Override
boolean preprocessEvent(InputDevice device, RawInputEvent event)

方法中,这个方法是KeyInputQueue中的一个虚函数,在处理按键事件之前的一个“预处理”。

PS:对HOME键的处理好像必需要修改PhoneWindowManager.java中的interceptKeyTi方法,具体可以参考对KeyGuard程序的处理。

 

===============================================================

 

系统底层事件处理过程


在系统启动后,android 会通过 

    static const char *device_path = "/dev/input";

    bool EventHub::penPlatformInput(void)

    res = scan_dir(device_path); 

通过下面的函数打开设备。

 
int EventHub::pen_device(const char *deviceName) 

    ... 
    fd = open(deviceName, O_RDWR); 
    ...  
    mFDs[mFDCount].fd = fd; 
    mFDs[mFDCount].events = POLLIN; 
    ... 
     ioctl (mFDs[mFDCount].fd, EVIOCGNAME(sizeof(devname)-1), devname); 
    ... 
    const char* root = getenv("ANDROID_ROOT"); 
    snprintf(keylayoutFilename, sizeof(keylayoutFilename), 
                 "%s/usr/keylayout/%s.kl", root, tmpfn); 
    ... 
    device->layoutMap->load(keylayoutFilename); 
    ... 

打开设备的时候,如果 device->classes&CLASS_KEYBOARD 不等于 0 表明是键盘。 

常用输入设备的定义有: 

enum { 
        CLASS_KEYBOARD      = 0x00000001, //键盘 

        CLASS_ALPHAKEY      = 0x00000002, // 

        CLASS_TOUCHSCREEN   = 0x00000004, //触摸屏 

        CLASS_TRACKBALL     = 0x00000008 //轨迹球 
}; 


打开键盘设备的时候通过上面的 ioctl 获得设备名称,命令字 EVIOCGNAME 的定义在文件: 

kernel/include/linux/input.h 中。 

#define EVIOCGNAME(len)   _IOC(_IOC_READ, 'E', 0x06, len) /* get device name */ 

内核键盘驱动文件 drivers/input/keyboard/pxa27x_keypad.c 中定义了设备名称 :pxa27x-keypad 

static struct platform_driver pxa27x_keypad_driver = { 

    .probe        = pxa27x_keypad_probe, 

    .remove        = __devexit_p(pxa27x_keypad_remove), 

    .suspend    = pxa27x_keypad_suspend, 

    .resume        = pxa27x_keypad_resume, 

    .driver        = { 

        .name    = "pxa27x-keypad", 

        .owner    = THIS_MODULE, 

    }, 

}; 

ANDROID_ROOT 为环境变量,在android的命令模式下通过 printenv 可以知道它为: system 

所以 keylayoutFilename 为:/system/usr/ keylayout/pxa27x-keypad.kl 

pxa27x-keypad.kl 定义了按键映射,具体内容如下:

 
# NUMERIC KEYS 3x4 
key 2   1 
key 3   2 
key 4   3 
key 5   4 
key 6   5 
key 7   6 
key 8   7 
key 9   8 
key 10 9 
key 11 0 
key 83 POUND 
key 55 STAR 

# FUNCTIONAL KEYS 
key 231 MENU        WAKE_DROPPED 
key 192 BACK           WAKE_DROPPED 
key 193 HOME       WAKE 
key 107 DEL        WAKE 
key 102 CALL        WAKE_DROPPED 
key 158 ENDCALL     WAKE_DROPPED 
key 28   DPAD_CENTER     WAKE 
key 115 VOLUME_UP 
key 114 VOLUME_DOWN 

如果没有定义键盘映射文件,那么默认使用系统的 /system/usr/keylayout/qwerty.kl 可以修改 /system/usr/keylayout/qwerty.kl 文件改变Android公司的按键映射。 

device->layoutMap->load(keylayoutFilename) 调用的是文件 KeyLayoutMap.cpp (frameworks\base\libs\ui)中的函数:

    status_t KeyLayoutMap::load(const char* filename)通过解析 pxa27x-keypad.kl 
把按键的映射关系保存在 :KeyedVector<int32_t,Key> m_keys; 中。 

当获得按键事件以后调用: 
status_t KeyLayoutMap::map(int32_t scancode, int32_t *keycode, uint32_t *flags) 

由映射关系 KeyedVector<int32_t,Key> m_keys 把扫描码转换成andorid上层可以识别的按键。



Android事件处理 

Init-----------zygote---------system-server-------------------windosmanager  ------------------------------------------------------------ UEventObserver
------------------------------------------------------------ InputDeviceRead
-------------------------------------------------------------InputDispatcher
-------------------------------------------------------------DisplayEventThr
-------------------------------------------------------------ActivityManager

EventHub:
而事件的传入是从EventHub开始的,EventHub是事件的抽象结构,维护着系统设备的运行情况,设备类型包括Keyboard、TouchScreen、TraceBall。它在系统启动的时候会通过open_device方法将系统提供的输入设备都增加到这个抽象结构中,并维护一个所有输入设备的文件描述符,如果输入设备是键盘的话还会读取/system/usr/keylayout/目录下对应键盘设备的映射文件,另外getEvent方法是对EventHub中的设备文件描述符使用poll操作等侍驱动层事件的发生,如果发生的事件是键盘事件,则调用 Map函数按照映射文件转换成相应的键值并将扫描码和键码返回给KeyInputQueue。
KeyLayoutMap主要是读取键盘映射文件并将键盘扫描码和键码进行转换

frameworks\base\core\jni\server\ com_android_server_KeyInputQueue.cpp
EventHub和KeyinputQueue的JNI接口层


KeyinputQueue:
在线程InputDeviceReader中会根据事件的类型以及事件值进行判断处理,从而确定这个事件对应的设备状态是否发生了改变并相应的改变对这个设备的描述结构InputDevice。
getEvent:在给定时间段时看是否有事件发生,如果有的话返回true否则false。

Windowmanager:
(frameworks/base/services/java/com/android/server/windowmanagerservice.java)
进程Windowmanager会创建一个线程(InputDispatcherThread),在这个线程里从事件队列中读取发生的事件(QueuedEvent ev = mQueue.getEvent()),并根据读取到事件类型的不同分成三类(KEYBOARD、TOUCHSCREEN、TRACKBALL),分别进行处理,例如键盘事件会调用dispatchKey((KeyEvent)ev.event, 0, 0)以将事件通过Binder发送给具有焦点的窗口应用程序,然后调用 mQueue.recycleEvent(ev)继续等侍键盘事件的发生;如果是触摸屏事件则调用dispatchPointer(ev, (MotionEvent)ev.event, 0, 0),这里会根据事件的种类(UP、DOWN、MOVE、OUT_SIDE等)进行判断并处理,比如Cancel或将事件发送到具有权限的指定的窗口中去;

Android 输入事件流程

EventHub

EventHub对输入设备进行了封装。输入设备驱动程序对用户空间应用程序提供一些设备文件,这些设备文件放在/dev/input里面。

EventHub扫描/dev/input下所有设备文件,并打开它们。


C代码
bool EventHub::openPlatformInput(void)   
{   
...   
    mFDCount = 1;   
    mFDs = (pollfd *)calloc(1, sizeof(mFDs[0]));   
    mDevices = (device_t **)calloc(1, sizeof(mDevices[0]));   
    mFDs[0].events = POLLIN;   
    mDevices[0] = NULL;   
  
    res = scan_dir(device_path);   
...   
    return true;   
}  
bool EventHub::openPlatformInput(void)
{
...
    mFDCount = 1;
    mFDs = (pollfd *)calloc(1, sizeof(mFDs[0]));
    mDevices = (device_t **)calloc(1, sizeof(mDevices[0]));
    mFDs[0].events = POLLIN;
    mDevices[0] = NULL;

    res = scan_dir(device_path);
...
    return true;
}

EventHub对外提供了一个函数用于从输入设备文件中读取数据。


C代码
bool EventHub::getEvent(int32_t* outDeviceId, int32_t* outType,   
        int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags,   
        int32_t* outValue, nsecs_t* outWhen)   
{   
    ...   
    while(1) {   
  
        // First, report any devices that had last been added/removed.   
        if (mClosingDevices != NULL) {   
            device_t* device = mClosingDevices;   
            LOGV("Reporting device closed: id=0x%x, name=%s\n",   
                 device->id, device->path.string());   
            mClosingDevices = device->next;   
            *outDeviceId = device->id;   
            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;   
            *outType = DEVICE_REMOVED;   
            delete device;   
            return true;   
        }   
        if (mOpeningDevices != NULL) {   
            device_t* device = mOpeningDevices;   
            LOGV("Reporting device opened: id=0x%x, name=%s\n",   
                 device->id, device->path.string());   
            mOpeningDevices = device->next;   
            *outDeviceId = device->id;   
            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;   
            *outType = DEVICE_ADDED;   
            return true;   
        }   
  
        release_wake_lock(WAKE_LOCK_ID);   
  
        pollres = poll(mFDs, mFDCount, -1);   
  
        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);   
  
        if (pollres <= 0) {   
            if (errno != EINTR) {   
                LOGW("select failed (errno=%d)\n", errno);   
                usleep(100000);   
            }   
            continue;   
        }   
  
        for(i = 1; i < mFDCount; i++) {   
            if(mFDs[i].revents) {   
                LOGV("revents for %d = 0x%08x", i, mFDs[i].revents);   
                if(mFDs[i].revents & POLLIN) {   
                    res = read(mFDs[i].fd, &iev, sizeof(iev));   
                    if (res == sizeof(iev)) {   
                        LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d",   
                             mDevices[i]->path.string(),   
                             (int) iev.time.tv_sec, (int) iev.time.tv_usec,   
                             iev.type, iev.code, iev.value);   
                        *outDeviceId = mDevices[i]->id;   
                        if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;   
                        *outType = iev.type;   
                        *outScancode = iev.code;   
                        if (iev.type == EV_KEY) {   
                            err = mDevices[i]->layoutMap->map(iev.code, outKeycode, outFlags);   
                            LOGV("iev.code=%d outKeycode=%d outFlags=0x%08x err=%d\n",   
                                iev.code, *outKeycode, *outFlags, err);   
                            if (err != 0) {   
                                *outKeycode = 0;   
                                *outFlags = 0;   
                            }   
                        } else {   
                            *outKeycode = iev.code;   
                        }   
                        *outValue = iev.value;   
                        *outWhen = s2ns(iev.time.tv_sec) + us2ns(iev.time.tv_usec);   
                        return true;   
                    } else {   
                        if (res<0) {   
                            LOGW("could not get event (errno=%d)", errno);   
                        } else {   
                            LOGE("could not get event (wrong size: %d)", res);   
                        }   
                        continue;   
                    }   
                }   
            }   
        }   
    ...   
}  
bool EventHub::getEvent(int32_t* outDeviceId, int32_t* outType,
        int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags,
        int32_t* outValue, nsecs_t* outWhen)
{
 ...
    while(1) {

        // First, report any devices that had last been added/removed.
        if (mClosingDevices != NULL) {
            device_t* device = mClosingDevices;
            LOGV("Reporting device closed: id=0x%x, name=%s\n",
                 device->id, device->path.string());
            mClosingDevices = device->next;
            *outDeviceId = device->id;
            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
            *outType = DEVICE_REMOVED;
            delete device;
            return true;
        }
        if (mOpeningDevices != NULL) {
            device_t* device = mOpeningDevices;
            LOGV("Reporting device opened: id=0x%x, name=%s\n",
                 device->id, device->path.string());
            mOpeningDevices = device->next;
            *outDeviceId = device->id;
            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
            *outType = DEVICE_ADDED;
            return true;
        }

        release_wake_lock(WAKE_LOCK_ID);

        pollres = poll(mFDs, mFDCount, -1);

        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);

        if (pollres <= 0) {
            if (errno != EINTR) {
                LOGW("select failed (errno=%d)\n", errno);
                usleep(100000);
            }
            continue;
        }

        for(i = 1; i < mFDCount; i++) {
            if(mFDs[i].revents) {
                LOGV("revents for %d = 0x%08x", i, mFDs[i].revents);
                if(mFDs[i].revents & POLLIN) {
                    res = read(mFDs[i].fd, &iev, sizeof(iev));
                    if (res == sizeof(iev)) {
                        LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d",
                             mDevices[i]->path.string(),
                             (int) iev.time.tv_sec, (int) iev.time.tv_usec,
                             iev.type, iev.code, iev.value);
                        *outDeviceId = mDevices[i]->id;
                        if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
                        *outType = iev.type;
                        *outScancode = iev.code;
                        if (iev.type == EV_KEY) {
                            err = mDevices[i]->layoutMap->map(iev.code, outKeycode, outFlags);
                            LOGV("iev.code=%d outKeycode=%d outFlags=0x%08x err=%d\n",
                                iev.code, *outKeycode, *outFlags, err);
                            if (err != 0) {
                                *outKeycode = 0;
                                *outFlags = 0;
                            }
                        } else {
                            *outKeycode = iev.code;
                        }
                        *outValue = iev.value;
                        *outWhen = s2ns(iev.time.tv_sec) + us2ns(iev.time.tv_usec);
                        return true;
                    } else {
                        if (res<0) {
                            LOGW("could not get event (errno=%d)", errno);
                        } else {
                            LOGE("could not get event (wrong size: %d)", res);
                        }
                        continue;
                    }
                }
            }
        }
 ...
}


对于按键事件,调用mDevices[i]->layoutMap->map进行映射。映射实际是由 KeyLayoutMap::map完成的,KeyLayoutMap类里读取配置文件qwerty.kl,由配置 文件 qwerty.kl 决定键值的映射关系。你可以通过修 改./development/emulator/keymaps/qwerty.kl来改变键值的映射关系。
JNI 函数

在frameworks/base/services/jni/com_android_server_KeyInputQueue.cpp文 件中,向 JAVA提供了函数android_server_KeyInputQueue_readEvent,用于读 取输入设备事件。


C代码
static jboolean   
android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz,   
                                          jobject event)   
{   
    gLock.lock();   
    sp hub = gHub;   
    if (hub == NULL) {   
        hub = new EventHub;   
        gHub = hub;   
    }   
    gLock.unlock();   
  
    int32_t deviceId;   
    int32_t type;   
    int32_t scancode, keycode;   
    uint32_t flags;   
    int32_t value;   
    nsecs_t when;   
    bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode,   
            &flags, &value, &when);   
  
    env->SetIntField(event, gInputOffsets.mDeviceId, (jint)deviceId);   
    env->SetIntField(event, gInputOffsets.mType, (jint)type);   
    env->SetIntField(event, gInputOffsets.mScancode, (jint)scancode);   
    env->SetIntField(event, gInputOffsets.mKeycode, (jint)keycode);   
    env->SetIntField(event, gInputOffsets.mFlags, (jint)flags);   
    env->SetIntField(event, gInputOffsets.mValue, value);   
    env->SetLongField(event, gInputOffsets.mWhen,   
                        (jlong)(nanoseconds_to_milliseconds(when)));   
  
    return res;   
}  
static jboolean
android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz,
                                          jobject event)
{
    gLock.lock();
    sp hub = gHub;
    if (hub == NULL) {
        hub = new EventHub;
        gHub = hub;
    }
    gLock.unlock();

    int32_t deviceId;
    int32_t type;
    int32_t scancode, keycode;
    uint32_t flags;
    int32_t value;
    nsecs_t when;
    bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode,
            &flags, &value, &when);

    env->SetIntField(event, gInputOffsets.mDeviceId, (jint)deviceId);
    env->SetIntField(event, gInputOffsets.mType, (jint)type);
    env->SetIntField(event, gInputOffsets.mScancode, (jint)scancode);
    env->SetIntField(event, gInputOffsets.mKeycode, (jint)keycode);
    env->SetIntField(event, gInputOffsets.mFlags, (jint)flags);
    env->SetIntField(event, gInputOffsets.mValue, value);
    env->SetLongField(event, gInputOffsets.mWhen,
                        (jlong)(nanoseconds_to_milliseconds(when)));

    return res;
}

readEvent调用hub->getEvent读了取事件,然后转换成JAVA的结构。
事件中转线程

在frameworks/base/services/java/com/android/server/KeyInputQueue.java 里创建了一个线程,它循环的读取事件,然后把事件放入事件队列里。


Java代码
Thread mThread = new Thread("InputDeviceReader") {   
        public void run() {   
            android.os.Process.setThreadPriority(   
                    android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);   
  
            try {   
                RawInputEvent ev = new RawInputEvent();   
                while (true) {   
                    InputDevice di;   
  
                    readEvent(ev);   
  
                    send = preprocessEvent(di, ev);   
                    addLocked(di, curTime, ev.flags, ..., me);   
                }   
        }   
    };  
Thread mThread = new Thread("InputDeviceReader") {
        public void run() {
            android.os.Process.setThreadPriority(
                    android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);

            try {
                RawInputEvent ev = new RawInputEvent();
                while (true) {
                    InputDevice di;

                    readEvent(ev);

                    send = preprocessEvent(di, ev);
                    addLocked(di, curTime, ev.flags, ..., me);
                }
        }
    };

输入事件分发线程

在frameworks/base/services/java/com/android/server/WindowManagerService.java里创建了一个输入事件分发线程,它负责把事件分发到相应的窗口上去。


Java代码
mQueue.getEvent   
dispatchKey/dispatchPointer/dispatchTrackball  
mQueue.getEvent
dispatchKey/dispatchPointer/dispatchTrackball

按键,触摸屏流程分析

按键触摸屏流程分析:
WindowManagerService类的构造函数
WindowManagerService()
  mQueue = new KeyQ();
因为 WindowManagerService.java (frameworks\base\services\java\com\android\server)中有:   
private class KeyQ extends KeyInputQueue
KeyQ 是抽象类  KeyInputQueue 的实现,所以 new KeyQ类的时候实际上在 KeyInputQueue 类中创建了
一个线程  InputDeviceReader 专门用来冲设备读取按键事件,代码:
Thread mThread = new Thread("InputDeviceReader") {
  public void run()
  {
        在循环中调用:readEvent(ev);
    ...
    send = preprocessEvent(di, ev);
        实际调用的是 KeyQ 类的 preprocessEvent 函数
    ...
    int keycode = rotateKeyCodeLocked(ev.keycode);
      int[] map = mKeyRotationMap;
      for (int i=0; i<N; i+=2)
      {
        if (map[i] == keyCode)
          return map[i+1];
      } //
    addLocked(di, curTime, ev.flags,RawInputEvent.CLASS_KEYBOARD,newKeyEvent(di, di.mDownTime, curTime, down,keycode, 0, scancode,...));
      QueuedEvent ev = obtainLocked(device, when, flags, classType, event);
  }
}

readEvent() 实际上调用的是 com_android_server_KeyInputQueue.cpp (frameworks\base\services\jni)中的:
static jboolean android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz,jobject event)
  bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode,&flags, &value, &when);
调用的是 EventHub.cpp (frameworks\base\libs\ui)中的:
bool EventHub::getEvent(int32_t* outDeviceId, int32_t* outType,
        int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags,
        int32_t* outValue, nsecs_t* outWhen)
在函数中调用了读设备操作:res = read(mFDs[i].fd, &iev, sizeof(iev));


在构造函数 WindowManagerService()调用 new KeyQ() 以后接着调用了:
  mInputThread = new InputDispatcherThread();      
  ...    
  mInputThread.start();
来启动一个线程  InputDispatcherThread
run()
  process();
    QueuedEvent ev = mQueue.getEvent(...)
因为WindowManagerService类中: final KeyQ mQueue;
所以实际上 InputDispatcherThread 线程实际上从  KeyQ 的事件队列中读取按键事件。
switch (ev.classType)
  case RawInputEvent.CLASS_KEYBOARD:
    ...
    dispatchKey((KeyEvent)ev.event, 0, 0);
    mQueue.recycleEvent(ev);
    break;
  case RawInputEvent.CLASS_TOUCHSCREEN:
    //Log.i(TAG, "Read next event " + ev);
    dispatchPointer(ev, (MotionEvent)ev.event, 0, 0);
    break;

===============================================================


KeyInputQueue.java (frameworks\base\services\java\com\android\server):
的线程  Thread mThread = new Thread("InputDeviceReader") 本地调用:
readEvent(ev);读取按键。readEvent 调用的是文件:
com_android_server_KeyInputQueue.cpp (frameworks\base\services\jni)中的函数:
static jboolean android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz,
                                          jobject event)
android_server_KeyInputQueue_readEvent中有:
hub = new EventHub;
bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode,
            &flags, &value, &when);

hub->getEvent 调用的是
EventHub.cpp (frameworks\base\libs\ui) 文件中的函数:
bool EventHub::getEvent(int32_t* outDeviceId, int32_t* outType,
        int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags,
        int32_t* outValue, nsecs_t* outWhen)
读取按键。

class RefBase::weakref_impl : public RefBase::weakref_type

在系统启动后,android 会通过
static const char *device_path = "/dev/input";
bool EventHub::openPlatformInput(void)
  res = scan_dir(device_path);


通过下面的函数打开设备。
int EventHub::open_device(const char *deviceName)
{
  ...
  fd = open(deviceName, O_RDWR);
  ...
  mFDs[mFDCount].fd = fd;
  mFDs[mFDCount].events = POLLIN;
  ...
  ioctl(mFDs[mFDCount].fd, EVIOCGNAME(sizeof(devname)-1), devname);
  ...
  const char* root = getenv("ANDROID_ROOT");
  snprintf(keylayoutFilename, sizeof(keylayoutFilename),
                 "%s/usr/keylayout/%s.kl", root, tmpfn);
  ...
  device->layoutMap->load(keylayoutFilename);
  ...
}
打开设备的时候,如果 device->classes&CLASS_KEYBOARD 不等于 0 表明是键盘。
常用输入设备的定义有:
enum {
        CLASS_KEYBOARD      = 0x00000001, //键盘
        CLASS_ALPHAKEY      = 0x00000002, //
        CLASS_TOUCHSCREEN   = 0x00000004, //触摸屏
        CLASS_TRACKBALL     = 0x00000008  //轨迹球
    };
打开键盘设备的时候通过上面的  ioctl 获得设备名称,命令字 EVIOCGNAME 的定义在文件:
kernel/include/linux/input.h 中。
#define EVIOCGNAME(len)   _IOC(_IOC_READ, 'E', 0x06, len) /* get device name */
在内核键盘驱动文件 drivers/input/keyboard/pxa27x_keypad.c 中定义了设备名称:pxa27x-keypad
static struct platform_driver pxa27x_keypad_driver = {
    .probe        = pxa27x_keypad_probe,
    .remove        = __devexit_p(pxa27x_keypad_remove),
    .suspend    = pxa27x_keypad_suspend,
    .resume        = pxa27x_keypad_resume,
    .driver        = {
        .name    = "pxa27x-keypad",
        .owner    = THIS_MODULE,
    },
};
ANDROID_ROOT 为环境变量,在android的命令模式下通过 printenv 可以知道它为: system
所以 keylayoutFilename 为:/system/usr/keylayout/pxa27x-keypad.kl
pxa27x-keypad.kl 定义了按键映射,具体内容如下:
----------------------
# NUMERIC KEYS 3x4
key 2   1
key 3   2
key 4   3
key 5   4
key 6   5
key 7   6
key 8   7
key 9   8
key 10  9
key 11  0
key 83  POUND
key 55  STAR

# FUNCTIONAL KEYS
key 231  MENU        WAKE_DROPPED
key 192  BACK           WAKE_DROPPED
key 193  HOME       WAKE
key 107  DEL        WAKE
key 102  CALL        WAKE_DROPPED
key 158  ENDCALL     WAKE_DROPPED
key 28   DPAD_CENTER     WAKE
key 115  VOLUME_UP
key 114  VOLUME_DOWN
----------------------
如果没有定义键盘映射文件,那么默认使用系统的 /system/usr/keylayout/qwerty.kl
可以修改 /system/usr/keylayout/qwerty.kl 文件改变Android公司的按键映射。

device->layoutMap->load(keylayoutFilename) 调用的是文件:
KeyLayoutMap.cpp (frameworks\base\libs\ui)中的函数:
status_t KeyLayoutMap::load(const char* filename)通过解析 pxa27x-keypad.kl
把按键的映射关系保存在 :KeyedVector<int32_t,Key> m_keys; 中。
当获得按键事件以后调用:
status_t KeyLayoutMap::map(int32_t scancode, int32_t *keycode, uint32_t *flags)
由映射关系 KeyedVector<int32_t,Key> m_keys 把扫描码转换成andorid上层可以识别的按键。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sijiangong/archive/2009/08/04/4407193.aspx

Android输入事件流程 

转载时请注明出处和作者联系方式
文章出处:http://www.limodev.cn/blog
作者联系方式:李先静 <xianjimli at hotmail dot com>

EventHub对输入设备进行了封装。输入设备驱动程序对用户空间应用程序提供一些设备文件,这些设备文件放在/dev/input里面。

EventHub扫描/dev/input下所有设备文件,并打开它们。

bool EventHub::openPlatformInput(void)

{

...

    mFDCount = 1;

    mFDs = (pollfd *)calloc(1, sizeof(mFDs[0]));

    mDevices = (device_t **)calloc(1, sizeof(mDevices[0]));

    mFDs[0].events = POLLIN;

    mDevices[0] = NULL;



    res = scan_dir(device_path);

...

    return true;

}

EventHub对外提供了一个函数用于从输入设备文件中读取数据。

bool EventHub::getEvent(int32_t* outDeviceId, int32_t* outType,

        int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags,

        int32_t* outValue, nsecs_t* outWhen)

{

	...

    while(1) {



        // First, report any devices that had last been added/removed.

        if (mClosingDevices != NULL) {

            device_t* device = mClosingDevices;

            LOGV("Reporting device closed: id=0x%x, name=%s\n",

                 device->id, device->path.string());

            mClosingDevices = device->next;

            *outDeviceId = device->id;

            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;

            *outType = DEVICE_REMOVED;

            delete device;

            return true;

        }

        if (mOpeningDevices != NULL) {

            device_t* device = mOpeningDevices;

            LOGV("Reporting device opened: id=0x%x, name=%s\n",

                 device->id, device->path.string());

            mOpeningDevices = device->next;

            *outDeviceId = device->id;

            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;

            *outType = DEVICE_ADDED;

            return true;

        }



        release_wake_lock(WAKE_LOCK_ID);



        pollres = poll(mFDs, mFDCount, -1);



        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);



        if (pollres <= 0) {

            if (errno != EINTR) {

                LOGW("select failed (errno=%d)\n", errno);

                usleep(100000);

            }

            continue;

        }



        for(i = 1; i < mFDCount; i++) {

            if(mFDs[i].revents) {

                LOGV("revents for %d = 0x%08x", i, mFDs[i].revents);

                if(mFDs[i].revents & POLLIN) {

                    res = read(mFDs[i].fd, &iev, sizeof(iev));

                    if (res == sizeof(iev)) {

                        LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d",

                             mDevices[i]->path.string(),

                             (int) iev.time.tv_sec, (int) iev.time.tv_usec,

                             iev.type, iev.code, iev.value);

                        *outDeviceId = mDevices[i]->id;

                        if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;

                        *outType = iev.type;

                        *outScancode = iev.code;

                        if (iev.type == EV_KEY) {

                            err = mDevices[i]->layoutMap->map(iev.code, outKeycode, outFlags);

                            LOGV("iev.code=%d outKeycode=%d outFlags=0x%08x err=%d\n",

                                iev.code, *outKeycode, *outFlags, err);

                            if (err != 0) {

                                *outKeycode = 0;

                                *outFlags = 0;

                            }

                        } else {

                            *outKeycode = iev.code;

                        }

                        *outValue = iev.value;

                        *outWhen = s2ns(iev.time.tv_sec) + us2ns(iev.time.tv_usec);

                        return true;

                    } else {

                        if (res<0) {

                            LOGW("could not get event (errno=%d)", errno);

                        } else {

                            LOGE("could not get event (wrong size: %d)", res);

                        }

                        continue;

                    }

                }

            }

        }

	...

}

对于按键事件,调用mDevices[i]->layoutMap->map进行映射。映射实际是由 KeyLayoutMap::map完成的,KeyLayoutMap类里读取配置文件qwerty.kl,由配置文件qwerty.kl决定键值的映射关系。你可以通过修改./development/emulator/keymaps/qwerty.kl来改变键值的映射关系。

JNI函数

在frameworks/base/services/jni/com_android_server_KeyInputQueue.cpp文件中,向JAVA提供了函数android_server_KeyInputQueue_readEvent,用于读取输入设备事件。

static jboolean

android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz,

                                          jobject event)

{

    gLock.lock();

    sp hub = gHub;

    if (hub == NULL) {

        hub = new EventHub;

        gHub = hub;

    }

    gLock.unlock();



    int32_t deviceId;

    int32_t type;

    int32_t scancode, keycode;

    uint32_t flags;

    int32_t value;

    nsecs_t when;

    bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode,

            &flags, &value, &when);



    env->SetIntField(event, gInputOffsets.mDeviceId, (jint)deviceId);

    env->SetIntField(event, gInputOffsets.mType, (jint)type);

    env->SetIntField(event, gInputOffsets.mScancode, (jint)scancode);

    env->SetIntField(event, gInputOffsets.mKeycode, (jint)keycode);

    env->SetIntField(event, gInputOffsets.mFlags, (jint)flags);

    env->SetIntField(event, gInputOffsets.mValue, value);

    env->SetLongField(event, gInputOffsets.mWhen,

                        (jlong)(nanoseconds_to_milliseconds(when)));



    return res;

}

readEvent调用hub->getEvent读了取事件,然后转换成JAVA的结构。




o 事件中转线程

在frameworks/base/services/java/com/android/server/KeyInputQueue.java里创建了一个线程,它循环的读取事件,然后把事件放入事件队列里。

    Thread mThread = new Thread("InputDeviceReader") {

        public void run() {

            android.os.Process.setThreadPriority(

                    android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);



            try {

                RawInputEvent ev = new RawInputEvent();

                while (true) {

                    InputDevice di;



                    readEvent(ev);



                    send = preprocessEvent(di, ev);

                    addLocked(di, curTime, ev.flags, ..., me);

                }

        }

    };





o 输入事件分发线程

在frameworks/base/services/java/com/android/server/WindowManagerService.java里创建了一个输入事件分发线程,它负责把事件分发到相应的窗口上去。

mQueue.getEvent

dispatchKey/dispatchPointer/dispatchTrackball
### 回答1: 可以使用tkinter模块中的bind()函数来更改键盘按键事件。具体步骤如下: 1. 导入tkinter模块: ```python import tkinter as tk ``` 2. 创建一个窗口对象: ```python root = tk.Tk() ``` 3. 创建一个文本框: ```python text = tk.Text(root) text.pack() ``` 4. 定义一个函数来处理键盘按键事件: ```python def handle_keypress(event): if event.keysym == 'Return': text.insert('end', '\n') else: text.insert('end', event.char) ``` 5. 绑定键盘按键事件到文本框: ```python text.bind('<Key>', handle_keypress) ``` 上面的代码将所有键盘按键事件都绑定到handle_keypress()函数上。 6. 进入主事件循环: ```python root.mainloop() ``` 上面的代码将使窗口保持打开状态,并且等待事件的发生。 这样,当用户在文本框中按下任何键盘按键时,handle_keypress()函数都会被调用,从而实现对键盘按键事件的处理。 ### 回答2: Tkinter是Python的一个图形界面库,可以用来创建各种窗口应用程序。要修改键盘按键事件,可以使用Tkinter提供的bind函数来实现。 首先,我们需要创建一个窗口,并在窗口上绑定一个键盘事件。例如,我们可以绑定一个按键按下的事件,当用户按下指定的按键时,触发相应的函数。可以使用窗口对象的bind函数来绑定键盘事件,将按键和相应的函数进行关联。 下面是一个简单的例子,演示了如何将按下的空格键与一个函数关联起来: ```python from tkinter import * # 创建一个窗口 root = Tk() # 定义按键按下的事件处理函数 def key_event(event): if event.keysym == 'space': print("你按下了空格键") # 绑定键盘事件 root.bind("<KeyPress>", key_event) # 运行窗口 root.mainloop() ``` 在这个例子中,我们创建了一个窗口,并在窗口上绑定了一个键盘按下事件。当用户按下空格键时,程序会执行key_event函数并输出一条消息。 除了绑定键盘按下事件以外,我们还可以绑定其它的键盘事件,比如键盘释放事件按键重复事件等。只需要修改bind函数的参数即可。 总而言之,通过使用Tkinter的bind函数,我们可以很方便地修改键盘按键事件,实现自定义的键盘操作。需要注意的是,不同的操作系统和键盘布局可能会导致按键的名称和行为不同,所以在编写程序时需要充分考虑这些因素。 ### 回答3: 在使用tkinter时,可以通过绑定键盘事件来实现对按键的更改。 首先,需要导入tkinter库,然后创建一个tkinter应用程序。在创建应用程序之后,可以使用bind方法来绑定键盘事件。bind方法需要两个参数,第一个参数是事件类型,可以是键盘按下事件("<KeyPress>")或键盘释放事件("<KeyRelease>"),第二个参数是处理事件的函数。 例如,如果我们想要更改回车键的功能,我们可以创建一个处理函数,然后将其绑定到"<KeyPress-Return>"事件上。在这个处理函数中,我们可以编写自定义的代码来实现所需的更改操作。 下面是一个简单的例子,演示如何使用tkinter更改回车键的功能: ```python import tkinter as tk def change_function(event): # 自定义更改的代码 print("回车键被按下") root = tk.Tk() # 绑定回车键的处理函数 root.bind("<KeyPress-Return>", change_function) root.mainloop() ``` 在这个例子中,当回车键被按下时,会触发change_function函数,该函数会输出一条消息。你可以根据自己的需要在这个函数中添加更改操作。 需要注意的是,该函数同时会响应按下和释放事件,如果你只想在按下事件或释放事件中触发处理函数,可以将事件类型改为"<KeyPress>"或"<KeyRelease>"。 通过上述方法,你可以实现对其他键盘按键的更改,只需要将事件类型和处理函数修改为相应的键盘事件和自定义的处理函数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值