Android 代码模拟触发事件总结

点击:
View.performClick()这个方法可以实现;每个View都继承这个方法,包括Button,Spinner等。
 
触屏:
public void myClickEvent(float x, float y) {
        long firstTime = SystemClock.uptimeMillis();
        final MotionEvent firstEvent = MotionEvent.obtain(firstTime, firstTime,
                MotionEvent.ACTION_DOWN, x, y, 0);
   
        long secondTime = firstTime + 30;
        final MotionEvent secondEvent = MotionEvent.obtain(secondTime,
                secondTime, MotionEvent.ACTION_UP, x, y, 0);

        dispatchTouchEvent(firstEvent);
        dispatchTouchEvent(secondEvent);
    }
注:(x,y)为View的坐标值
 
滑屏:
public void myFlingEvent(float x, float y) {
        long firstTime = SystemClock.uptimeMillis();
        final MotionEvent firstEvent = MotionEvent.obtain(firstTime, firstTime,
                MotionEvent.ACTION_DOWN, x, y, 0);
   
        long secondTime = firstTime + 30;
        final MotionEvent secondEvent = MotionEvent.obtain(secondTime,
                secondTime, MotionEvent.ACTION_MOVE, x, y, 0);
        long thirdTime = secondTime + 30;
        final MotionEvent secondEvent = MotionEvent.obtain(secondTime,
                secondTime, MotionEvent.ACTION_UP, x+30, y+30, 0);
        dispatchTouchEvent(firstEvent);
        dispatchTouchEvent(secondEvent);
        dispatchTouchEvent(thirdEvent);
    }
注:(x,y)为View的坐标值


后退:

我测试发现,有两种方法可行。
①、java.lang.Runtime

Runtime runtime = Runtime.getRuntime();

runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);

②、android.app.Instrumentation

Instrumentation inst = new Instrumentation();

inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);


转载请注明出处:http://blog.csdn.net/yangxi_001/article/details/8946157
 

你可能感兴趣的:(Android 代码模拟触发事件总结)