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
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值