简介
Android系统是基于Linux内核的,而Linux内核继承和兼容了丰富的Unix系统进程间通信(IPC)机制。Binder其实也不是Android提出来的一套新的进程间通信机制,它是基于OpenBinder来实现的。Binder是一种进程间通信机制,它是一种类似于COM和CORBA分布式组件架构,通俗一点,其实是提供远程过程调用(RPC)功能。
功能
向其它进程注入事件,比如触屏、单击、按键等人为事件。
我们已经知道了Android系统进程交互是采用什么机制了。那么如何实现进程交互?他的原理是什么?
原理是通过app操作手机超级终端命令来向系统驱动写命令实现。
模拟原理是对驱动发送消息,就是linux里面的input子系统。
命令格式: sendevent /dev/input/eventX [type] [key] [value]
其中/dev/input/eventX 对应的是设备,可以用getevent查看可用设备。
实现
1、获取真机设备事件信息,这可以参考获取小米设备信息的文章。
2、通过程序向手机超级终端写入命令。(注意:需要获取root权限)
代码
关键代码如下:
String[] commands = new String[5];
Log.d(PBConstants.TAG, "z=" + z);
z = 0;
commands[0] = "sendevent /dev/input/event" + z + " 1 116 1";
commands[1] = "sendevent /dev/input/event" + z + " 0 0 0";
commands[2] = "sleep 1";
commands[3] = "sendevent /dev/input/event" + z + " 1 116 0";
commands[4] = "sendevent /dev/input/event" + z + " 0 0 0";
Process suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
// Execute commands that require root access
for (int i = 0; i < 5; i++) {
os.writeBytes(commands[i] + "\n");
os.flush();
}
os.writeBytes("exit\n");
os.flush();
String[] commands = new String[9];
event_id++;
commands[0] = "sendevent /dev/input/event" + 1 + " 3 57 " + event_id;
commands[1] = "sendevent /dev/input/event" + 1 + " 3 57 0";
commands[2] = "Sleep 1";
commands[3] = "sendevent /dev/input/event" + 1 + " 3 53 " + x;
commands[4] = "sendevent /dev/input/event" + 1 + " 3 54 " + y;
commands[5] = "sendevent /dev/input/event" + 1 + " 0 0 0";
commands[6] = "Sleep 1";
commands[7] = "sendevent /dev/input/event" + 1 + " 3 57 4294967295";
commands[8] = "sendevent /dev/input/event" + 1 + " 0 0 0";
Process suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
// Execute commands that require root access
for (int i = 0; i < 9; i++) {
os.writeBytes(commands[i] + "\n");
os.flush();
}
os.writeBytes("exit\n");
os.flush();
Process suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
os.writeBytes("input keyevent KEYCODE_MENU\n");
os.writeBytes("exit\n");
os.flush();
return ((suProcess.waitFor() != 255) ? true : false);