Androidはjavaコードでユーザーのクリックと長押しをシミュレートします

1933 ワード

直接コードをつけて、注釈は私が書いたのがとても詳しいです
    /**
     *     ,  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();
    }