Search code examples
androidaccessibilityservice

How can I disable the action of pressed key by onKeyEvent on accessibility service?


I'm developing an android app which modifies actions of pressed keys (VOLUME_UP , VOLUME_DOWN, KEYENTER)

I have a selfie stick controller which has three buttons. I can detect which button pressed and I can something what I want to do without disable original key event of pressed key

I need to disable original key event of pressed button.

My service tag is like this in Android Manifest :

<service android:name=".CustomListener"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
        android:label="@string/accessibility_service_label">
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService" />
        </intent-filter>
        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/accessibility_service_config" />
    </service>

And my accesibility_service_config like this :

xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackAllMask"
android:accessibilityFlags="flagRequestFilterKeyEvents"
android:canRequestFilterKeyEvents="true"
android:canRetrieveWindowContent="true"
android:notificationTimeout="50"
android:packageNames="com.custom333.clevent"

And my onKeyevent function is :

@Override
protected boolean onKeyEvent(KeyEvent event) {
    int keyCode = event.getKeyCode();

    KeyEvent.KEYCODE_META_RIGHT
    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            Log.d("##CURRENTKEY", "Volume -");

        case KeyEvent.KEYCODE_VOLUME_UP:
            Log.d("##CURRENTKEY", "Volume +");
            return false;
    }
    return super.onKeyEvent(event);
}

With this code, I can get the pressed key but I can not disable original key events.

Is there anyone can help me about this?


Solution

  • Try to return "true" instead of "return super.onKeyEvent(event);" As documentation says, onKeyEvent is a filter and receives events' copies. So if we are going to consume the event - we should return "true" and "false" if only "observing".