Android通过java代码模拟用户点击和长按

直接上代码,注释我写的很详细

    /**
     * 模拟点击,限定View,无论坐标传什么View都会响应点击事件
     * @param view  要点击的View
     * @param x     x方向像素
     * @param y     y方向像素
     * @param delayTime     按下和抬起时间差,用于区分点击和长按,不同定制系统可能不一样(redmi 6pro为400ms)
     */

    private void simulateViewClick(final View view, final int x, final int y, int delayTime) {
        //按下
        long downTime = SystemClock.uptimeMillis();
        final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,MotionEvent.ACTION_DOWN, x, y, 0);
        view.onTouchEvent(downEvent);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //抬起
                final MotionEvent upEvent = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),MotionEvent.ACTION_UP, x, y, 0);
                view.onTouchEvent(upEvent);
                upEvent.recycle();

            }
        }, delayTime);
        downEvent.recycle();
    }


    /**
     * 模拟屏幕点击
     * @param x     x方向像素
     * @param y     y方向像素
     * @param delayTime     按下和抬起时间差,用于区分点击和长按,不同定制系统可能不一样(redmi 6pro为400ms)
     */
    public void simulateScreenClick(final int x, final int y, int delayTime){
        // 按下
        final MotionEvent evenDownt = MotionEvent.obtain(System.currentTimeMillis(),
                System.currentTimeMillis() + 100, MotionEvent.ACTION_DOWN, x, y, 0);
        dispatchTouchEvent(evenDownt);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 抬起
                final MotionEvent eventUp = MotionEvent.obtain(System.currentTimeMillis(),
                        System.currentTimeMillis()+100, MotionEvent.ACTION_UP, x, y, 0);
                dispatchTouchEvent(eventUp);
                eventUp.recycle();
            }
        }, delayTime);
        evenDownt.recycle();
    }

 

你可能感兴趣的:(android)