Android模拟点击的两种方式
导论
在Android中模拟一个点击事件有两种方式是通过模拟MotionEvent来实现;一种是通过ADB来实现
第一种:模拟MotionEvent
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(); }
Demo:
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(); } }
第二种:ADB控制
The sources are: trackball joystick touchnavigation mouse keyboard gamepad touchpad dpad stylus touchscreen The 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)
Demo 输入按键enter key:
adb shell input keyevent 66
Demo 输入输入滑动操作:
adb shell input touchscreen swipe 18 665 18 350
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。