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

相关推荐
绵羊202330 分钟前
单细胞转录组测序上游——cellranger
linux
Awkwardx3 小时前
Linux系统编程—线程同步与互斥
linux·服务器
赖small强4 小时前
[Linux]内核队列实现详解
linux·kfifo·请求队列·工作队列(workqueue)·等待队列·kfifo_init
晨陌y5 小时前
深入剖析:仓颉语言的性能优化核心技术
android·性能优化·仓颉
xhbh6665 小时前
【实战总结】MySQL日期加减大全:日期计算、边界处理与性能优化详解
android
00后程序员张5 小时前
如何提高 IPA 安全性 多工具组合打造可复用的 iOS 加固与反编译防护体系(IPA 安全 iOS 加固 无源码混淆 Ipa Guard 实战)
android·安全·ios·小程序·uni-app·iphone·webview
张拭心6 小时前
“不卷 AI、不碰币、下班不收消息”——Android 知名技术大牛 Jake Wharton 的求职价值观
android·前端·aigc
www.026 小时前
linux服务器升级显卡驱动(笔记)
linux·运维·服务器·笔记·ubuntu·服务器环境
wdfk_prog6 小时前
[Linux]学习笔记系列 -- [kernel][time]hrtimer
linux·笔记·学习
摇滚侠6 小时前
Spring Boot3零基础教程,把 Java 程序打包为 Linux 可执行文件,笔记91
java·linux·笔记