Android自动化测试初探(四): 模拟键盘鼠标事件(Socket+Instrumentation实现)

字体:小中大 |上一篇下一篇|打印 |我要投稿 |推荐标签:Androidandroid软件测试技术自动化测试

  通过Socket + Instrumentation实现模拟键盘鼠标事件主要通过以下三个部分组成:

  * Socket编程:实现PC和Emulator通讯,并进行循环监听

  * Service服务:将Socket的监听程序放在Service中,从而达到后台运行的目的。这里要说明的是启动服务有两种方式,bindService和startService,两者的区别是,前者会使启动的Service随着启动Service的Activity的消亡而消亡,而startService则不会这样,除非显式调用stopService,否则一直会在后台运行因为Service需要通过一个Activity来进行启动,所以采用startService更适合当前的情形

  * Instrumentation发送键盘鼠标事件:Instrumentation提供了丰富的以send开头的函数接口来实现模拟键盘鼠标,如下所述:

  sendCharacterSync(int keyCode) //用于发送指定KeyCode的按键

  sendKeyDownUpSync(int key) //用于发送指定KeyCode的按键

  sendPointerSync(MotionEvent event) //用于模拟Touch

  sendStringSync(String text) //用于发送字符串

  注意:以上函数必须通过Message的形式抛到Message队列中。如果直接进行调用加会导致程序崩溃。

  对于Socket编程和Service网上有很多成功的范例,此文不再累述,下面着重介绍一下发送键盘鼠标模拟事件的代码:

  1.发送键盘KeyCode:

  步骤1. 声明类handler变量

private static Handler handler;

  步骤2. 循环处理Message

//在Activity的onCreate方法中对下列函数进行调用
private void createMessageHandleThread(){
//need start a thread to raise looper, otherwise it will be blocked
Thread t = new Thread() {
public void run() {
Log.i( TAG,"Creating handler ..." );
Looper.prepare();
handler = new Handler(){
public void handleMessage(Message msg) {
//process incoming messages here
}
};
Looper.loop();
Log.i( TAG, "Looper thread ends" );
}
};
t.start();
}

  步骤3. 在接收到Socket中的传递信息后抛出Message

handler.post( new Runnable() {
public void run() {
Instrumentation inst=new Instrumentation();
inst.sendKeyDownUpSync(keyCode);
}
} );

  2.Touch指定坐标,如下例子即touch point(240,400)

Instrumentation inst=new Instrumentation();
inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 240, 400, 0));
inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 240, 400, 0));

  3.模拟滑动轨迹

  将上述方法中间添加 MotionEvent.ACTION_MOVE

转自: http://www.51testing.com/html/13/n-215813.html

更多相关文章

  1. android自动化测试工具简介
  2. Android事件分发和View绘制流程分析(三)
  3. android onTouch事件的派发
  4. Android ListView嵌套Button,Button事件覆盖item事件解决办法
  5. Android 事件中 OnTouch 事件
  6. android 为TextView的部分文字设置超链接样式并监听点击事件
  7. Android 你的OnTouchEvent() 触屏事件的优化了吗
  8. 如何在Android中在fragment中实现点击按钮事件?

随机推荐

  1. jvm系列(1)内存结构(补充版)
  2. java关键字系列(3)final
  3. 数据结构与算法(5)队列
  4. 设计模式(1)单例模式
  5. java中的注解,真的很重要,别不会用了
  6. 设计模式之门面模式
  7. java创建对象的过程(内存角度分析)
  8. java集合系列(2)collection
  9. jvm系列(3)类加载机制
  10. 数据结构与算法(3)链表