1、建立与手机的socket连接
每个AdbChimpDevice对象内保存着一个ChimpManager对象
而每个终端对应着一个AdbChimpDevice对象
ChimpManager manager = createManager("127.0.0.1", 12345);
private ChimpManager createManager(String address, int port) {
device.createForward(port, port); //device为IDevice对象,具体实现见ddmslib内的IDevice.java与Device.java
String command = "monkey --port " + port;
executeAsyncCommand(command, new LoggingOutputReceiver(LOG, Level.FINE));
// Sleep for a second to give the command time to execute.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOG.log(Level.SEVERE, "Unable to sleep", e);
}
InetAddress addr;
try {
addr = InetAddress.getByName(address);
} catch (UnknownHostException e) {
LOG.log(Level.SEVERE, "Unable to convert address into InetAddress: " + address, e);
return null;
}
// We have a tough problem to solve here. "monkey" on the device gives us no indication
// when it has started up and is ready to serve traffic. If you try too soon, commands
// will fail. To remedy this, we will keep trying until a single command (in this case,
// wake) succeeds.
boolean success = false;
ChimpManager mm = null;
long start = System.currentTimeMillis();
while (!success) {
long now = System.currentTimeMillis();
long diff = now - start;
if (diff > MANAGER_CREATE_TIMEOUT_MS) {
LOG.severe("Timeout while trying to create chimp mananger");
return null;
}
try {
Thread.sleep(MANAGER_CREATE_WAIT_TIME_MS);
} catch (InterruptedException e) {
LOG.log(Level.SEVERE, "Unable to sleep", e);
}
Socket monkeySocket;
try {
monkeySocket = new Socket(addr, port);
} catch (IOException e) {
LOG.log(Level.FINE, "Unable to connect socket", e);
success = false;
continue;
}
try {
mm = new ChimpManager(monkeySocket);
} catch (IOException e) {
LOG.log(Level.SEVERE, "Unable to open writer and reader to socket");
continue;
}
try {
mm.wake();
} catch (IOException e) {
LOG.log(Level.FINE, "Unable to wake up device", e);
success = false;
continue;
}
success = true;
}
return mm;
}
执行Press或Touch的实现在manger内,具体实现见下
2、向手机发送命令,实现触屏与按键操作
//在ChimpManager.java中
发送按键消息的命令为: "key down " + name
"key up " + name
发送触屏消息的命令: "touch up " + x + " " + y
"touch down " + x + " " + y
"touch move " + x + " " + y
对消息的执行函数:
BufferedWriter monkeyWriter = new BufferedWriter(new OutputStreamWriter(monkeySocket.getOutputStream()));
command = command.trim(); // common为上面的命令,String类型
monkeyWriter.write(command + "\n");
monkeyWriter.flush();
注:com.google.common.*是在google guava库文件中,下载地址:http://code.google.com/p/guava-libraries/