Eventos de simulación de comandos de entrada de Android e implementación de inyección de eventos

parámetros del comando de entrada

Ingrese adb shell y escriba inputpara ver la ayuda del comando

127|emulator_x86_64:/ # input                                                  
Usage: input [<source>] [-d DISPLAY_ID] <command> [<arg>...]

The sources are: 
      touchnavigation
      touchscreen
      joystick
      stylus
      touchpad
      gamepad
      dpad
      mouse
      keyboard
      trackball

-d: specify the display ID.
      (Default: -1 for key event, 0 for motion event if not specified.)
The commands and default sources are:
      text <string> (Default: touchscreen)
      keyevent [--longpress|--doubletap] <key code number or name> ... (Default: keyboard)
      tap <x> <y> (Default: touchscreen)
      swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
      draganddrop <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
      press (Default: trackball)
      roll <dx> <dy> (Default: trackball)
      motionevent <DOWN|UP|MOVE|CANCEL> <x> <y> (Default: touchscreen)
      keycombination [-t duration(ms)] <key code 1> <key code 2> ... (Default: keyboard, the key order is important here.)

Ruta del código: frameworks/base/services/core/java/com/android/server/input/InputShellCommand.java
Por ejemplo: adb shell input tap 500 100
simule un evento de clic en la posición de las coordenadas (500,100).
El evento de clic de toque corresponde al código fuente:

    private void sendTap(int inputSource, float x, float y, int displayId) {
    
    
        final long now = SystemClock.uptimeMillis();
        injectMotionEvent(inputSource, MotionEvent.ACTION_DOWN, now, now, x, y, 1.0f,
                displayId);
        injectMotionEvent(inputSource, MotionEvent.ACTION_UP, now, now, x, y, 0.0f, displayId);
    }

Análisis de parámetros:
int inputSource: indica el tipo de evento de simulación
float x, float y: indica el punto de coordenadas del evento
int displayId: en qué pantalla se activa el evento (generalmente usado para múltiples pantallas)

Inyección de evento táctil

        btn.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                Log.i("TAG:","onClick");
                injectClick();
            }
        });
        void injectClick() {
    
    
        Log.i("TAG:","injectClick");
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                Instrumentation instrumentation = new Instrumentation();
                final long now = SystemClock.uptimeMillis();
                int action = MotionEvent.ACTION_DOWN;
                float x = 500;
                float y = 100;
                MotionEvent clickDown = MotionEvent.obtain(now,now,action,x,y,0);
                instrumentation.sendPointerSync(clickDown);
                action = MotionEvent.ACTION_UP;
                MotionEvent clickUp = MotionEvent.obtain(now,now,action,x,y,0);
                instrumentation.sendPointerSync(clickUp);
            }
        }).start();
    }

Haga clic en un botón y haga clic en el evento correspondiente en las coordenadas (500,100)

inyección de evento clave

        btn.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                Log.i("TAG:","onClick");
                injectHome();
            }
        });
		void injectHome() {
    
    
		        Log.i("TAG:","injectHome");
		        new Thread(new Runnable() {
    
    
		            @Override
		            public void run() {
    
    
		                Instrumentation instrumentation = new Instrumentation();
		                final long now = SystemClock.uptimeMillis();
		                int action = KeyEvent.ACTION_DOWN;
		                KeyEvent homeDown = new KeyEvent(action,KeyEvent.KEYCODE_HOME);
		                instrumentation.sendKeySync(homeDown);
		                action = KeyEvent.ACTION_UP;
		                KeyEvent homeUp = new KeyEvent(action,KeyEvent.KEYCODE_HOME);
		                instrumentation.sendKeySync(homeUp);
		
		            }
		        }).start();
		    }

Haga clic en un botón, correspondiente al evento HOME

Problema de permiso de inyección de eventos

También tenemos permiso para informar errores en las aplicaciones que escribimos.

Insertar descripción de la imagen aquí

Ver marcos de código fuente de AndroidManifest/base/core/res/AndroidManifest.xml

    <!-- @SystemApi Allows an application to inject user events (keys, touch, trackball)
         into the event stream and deliver them to ANY window.  Without this
         permission, you can only deliver events to windows in your own process.
         <p>Not for use by third-party applications.
         @hide
    -->
    <permission android:name="android.permission.INJECT_EVENTS"
        android:protectionLevel="signature" />

Del código fuente se puede ver que las aplicaciones de terceros no pueden utilizar este permiso.

Solucionar problemas de permisos

Resuelva el problema de permisos creando aplicaciones integradas
1. Cree la carpeta correspondiente en el directorio paquete/apps/, como por ejemplo: MyInject
2. Compile el apk en Android Studio, cree un archivo mk y colóquelo en esta carpeta para su
Insertar descripción de la imagen aquí
configuración . archivo mk

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := MyInject
LOCAL_MODULE_TAGS := optional 
LOCAL_SRC_FILES := $(LOCAL_MODULE).apk
LOCAL_MODULE_CLASS := APPS
LOCAL_MODULE_SUFFIX := $(COMMON_ANDROID_PACKAGE_SUFFIX)
#LOCAL_CERTIFICATE := PRESIGNED
LOCAL_CERTIFICATE := platform
include $(BUILD_PREBUILT)

3. Compilar apk

. build/envsetup.sh
lunch sdk_phone_x86_64 #must this
make MyInject

4. Instale
el apk integrado en out/target/product/emulator_x86_64/system/app/MyInject/el directorio
e adb install MyInject.apkinstálelo.

Supongo que te gusta

Origin blog.csdn.net/yimelancholy/article/details/130496623
Recomendado
Clasificación