在Android中模拟一个点击事件有三种方式是通过模拟MotionEvent来实现;一种是通过ADB来实现;一种是通过Instrumentation测试框架来实现
private void setSimulateClick(View view, float x, float y) { long downTime = SystemClock.uptimeMillis(); final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0); downTime += 1000; final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_UP, x, y, 0); view.onTouchEvent(downEvent); view.onTouchEvent(upEvent); downEvent.recycle(); upEvent.recycle(); }
package com.xys.simulateevent;import android.app.Activity;import android.os.Bundle;import android.os.SystemClock;import android.view.MotionEvent;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); } public void clickeMe(View view) { Toast.makeText(this, "clicked", Toast.LENGTH_LONG).show(); } public void simulate(View view) { setSimulateClick(button, 160, 100); } private void setSimulateClick(View view, float x, float y) { long downTime = SystemClock.uptimeMillis(); final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0); downTime += 1000; final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_UP, x, y, 0); view.onTouchEvent(downEvent); view.onTouchEvent(upEvent); downEvent.recycle(); upEvent.recycle(); }}
The sources are: trackball joystick touchnavigation mouse keyboard gamepad touchpad dpad stylus touchscreenThe commands and default sources are: text <string> (Default: touchscreen) keyevent [--longpress] <key code number or name> ... (Default: keyboard) tap <x> <y> (Default: touchscreen) swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen) press (Default: trackball) roll <dx> <dy> (Default: trackball)
adb shell input keyevent 66
adb shell input touchscreen swipe 18 665 18 350
//KeyEvent.KEYCODE_MENU //KeyEvent.KEYCODE_BACK public static void sendKeyEvent(final int KeyCode) { new Thread() { //不可在主线程中调用 public void run() { try { Instrumentation inst = new Instrumentation(); inst.sendKeyDownUpSync(KeyCode); } catch (Exception e) { e.printStackTrace(); } } }.start(); }