Simulate a mouse input on android

2019-03-21 22:42发布

问题:

Imagine that I have a service that receives coordinates from a bluetooth device, now I want to display a mouse cursor whenever it moves.

I managed to send MotionEvents with a toolType = TOOL_TYPE_MOUSE but I don't get the native android mouse cursor displayed on screen.

The events I am sending look like these:

05-14 13:38:05.043: I/onTouchEvent(30301): MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=498.0, y[0]=996.0, toolType[0]=TOOL_TYPE_MOUSE, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=251957430, downTime=251957420, deviceId=1, source=0x2002 }

I am creating them like this:

  public void moveMouse(int x, int y)   {

        // Obtain MotionEvent object
        long downTime = SystemClock.uptimeMillis() - 10;
        long eventTime = SystemClock.uptimeMillis();
        int metaState = 0;
        MotionEvent.PointerProperties p = new PointerProperties();
        p.toolType = MotionEvent.TOOL_TYPE_MOUSE;
        p.id = 0;
        MotionEvent.PointerProperties[] properties = {p};

        MotionEvent.PointerCoords c = new MotionEvent.PointerCoords();
        c.x = x;
        c.y = y;
        c.orientation = 0f;
        c.pressure = 1f;
        c.size = 1f;

        MotionEvent.PointerCoords[] coords = {c};
        int buttonState = 0;
        float precisionX = 1.0f;
        float precisionY = 1.0f;
        int deviceId = 1;
        int edgeFlags = 0;
        int flags = 0;

        MotionEvent event;
        event =
                MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, 1, properties,
                        coords, metaState, buttonState, precisionX, precisionY, deviceId,
                        edgeFlags, InputDevice.SOURCE_MOUSE, flags);

    dispatchTouchEvent(event);

But I still can't see the mouse pointer. What am I doing wrong?