C语言实现android/linux按键模拟

C语言实现 input事件模拟

c 复制代码
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>

int main() {
    int fd = open("/dev/input/event0", O_RDWR);
    if (fd < 0) {
        perror("Failed to open device");
        return -1;
    }

    // 定义 8 个输入事件(按顺序模拟按键按下和释放)
    struct input_event events[] = {
        // KEY_314 按下
        {.type = EV_KEY, .code = 314, .value = 1},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0},
        // KEY_212 按下
        {.type = EV_KEY, .code = 212, .value = 1},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0},
        // KEY_212 释放
        {.type = EV_KEY, .code = 212, .value = 0},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0},
        // KEY_314 释放
        {.type = EV_KEY, .code = 314, .value = 0},
        {.type = EV_SYN, .code = SYN_REPORT, .value = 0}
    };

    // 批量发送事件
    for (int i = 0; i < sizeof(events)/sizeof(events[0]); i++) {
        if (write(fd, &events[i], sizeof(struct input_event)) < 0) {
            perror("Failed to send event");
            close(fd);
            return -1;
        }
    }

    close(fd);
    return 0;
}

静态交叉编译

c 复制代码
aarch64-linux-gnu-gcc-10   123.c -o startup_camera_common --static

可以模拟 简单按键事件

为什么不用 shell命令

比如

adb shell "sendevent /dev/input/event0 0001 314 00000001"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

adb shell "sendevent /dev/input/event0 0001 212 00000001"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

adb shell "sendevent /dev/input/event0 0001 212 00000000"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

adb shell "sendevent /dev/input/event0 0001 314 00000000"

adb shell "sendevent /dev/input/event0 0000 0000 00000000"

sendevent 是 busybox命令, 每次执行八条命令 耗时过长, 在抓 perfetto的时候 会看到耗时特别久, 对于分析按键触发的性能事件有很大的干扰!

相关推荐
UNbuff_021 分钟前
Linux ip 命令使用指南
linux·网络·tcp/ip
努力努力再努力wz24 分钟前
【C++进阶系列】:万字详解红黑树(附模拟实现的源码)
java·linux·运维·c语言·开发语言·c++
路弥行至28 分钟前
从0°到180°,STM32玩转MG996R舵机
c语言·数据库·stm32·单片机·嵌入式硬件·mcu·mongodb
会飞的土拨鼠呀28 分钟前
Linux负载如何判断服务器的压力
linux·服务器·php
王璐WL31 分钟前
【C语言入门级教学】内存函数
c语言·开发语言·算法
恋猫de小郭32 分钟前
Flutter Riverpod 3.0 发布,大规模重构下的全新状态管理框架
android·前端·flutter
zhongwenhua52033 分钟前
tina linux新增mpp程序
linux·mpp·v853
纤瘦的鲸鱼1 小时前
MySQL慢查询
android·adb
白鹭1 小时前
apache详细讲解(apache介绍+apache配置实验+apache实现https网站)
linux·运维·apache·apache配置·apache实现https网站
郭庆汝1 小时前
模型部署:(三)安卓端部署Yolov8-v8.2.99目标检测项目全流程记录
android·yolo·目标检测·yolov8