android如何通过cpp sendevent发送powerkey按键消息

前言

客户希望通过cpp发送powerkey来进行系统的休眠唤醒

代码实现

参考adb shell sendevent 实现。sendevent.c 参考代码在external/toybox/toys/android/sendevent.c

实现方式比较简单,直接上代码

#include 
#include 
#include 
#include 
#include 

//std::mutex g_mutex;

int main() {
    //std::lock_guard lock(g_mutex);
    int fd = open("/dev/input/event0", O_WRONLY | O_NONBLOCK);
    if (fd < 0) {
        printf("Failed to open input device\n");
        return -1;
    }    
    struct input_event event;
    event.type = EV_KEY;
    event.code = KEY_POWER;
    event.value = 1; // 按下1
    if (write(fd, &event, sizeof(struct input_event)) < 0) {
        printf("Failed to send key press event\n");
        close(fd);
        return -1;
    }

    event.type = EV_SYN;
    event.code = KEY_RESERVED;
    event.value = 0; // 按下2
    if (write(fd, &event, sizeof(struct input_event)) < 0) {
        printf("Failed to send key press event\n");
        close(fd);
        return -1;
    }    
    //usleep(500000); // 等待 500 毫秒
    //usleep(500000);
    event.type = EV_KEY;
    event.code = KEY_POWER;
    event.value = 0; // 松开1
    if (write(fd, &event, sizeof(struct input_event)) < 0) {
        printf("Failed to send key release event\n");
        close(fd);
        return -1;
    }

    event.type = EV_SYN;
    event.code = KEY_RESERVED;
    event.value = 0; // 松开2
    if (write(fd, &event, sizeof(struct input_event)) < 0) {
        printf("Failed to send key release event\n");
        close(fd);
        return -1;
    }
    close(fd);
    return 0;
}

你可能感兴趣的:(android)