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的时候 会看到耗时特别久, 对于分析按键触发的性能事件有很大的干扰!

相关推荐
DFT计算杂谈3 小时前
无 Root 权限在 Tesla K80 零门槛部署 DeepSeek 大模型
linux·服务器·网络·数据库·机器学习
人邮异步社区3 小时前
怎么把C语言学到精通?
c语言·开发语言
执明wa4 小时前
LayoutInflater详解: XML是如何变成View的?
android·xml·开发语言·android studio
Zhang~Ling4 小时前
从 fopen 到 struct file:从零开始拆解 Linux 文件 I/O
linux·运维·服务器
DeeplyMind4 小时前
Linux 深入 per-VMA lock:Linux 缺页路径如何摆脱 mmap_lock
linux·per-vma lock
爱写代码的森4 小时前
蒙三方库 | harmony-utils之FileUtil文件重命名与属性查询详解
linux·运维·服务器·华为·harmonyos·鸿蒙·huawei
404_coder5 小时前
源码视角下的 Android 开机流程:从 Zygote、SystemServer 到 Launcher
android
二流小码农5 小时前
鸿蒙开发:以登录案例了解代码架构MVVM
android·ios·harmonyos
XMAIPC_Robot5 小时前
软硬协同实时控制|RK3588业务调度+FPGA硬件时序,ethercat实现半导体设备微秒级响应(125us)
linux·arm开发·人工智能·fpga开发
用户69371750013846 小时前
从代码生产者到 AI 协作者:软件工程师的角色重构
android·前端·后端