'How do I detect back/home press in an accessibility Service?

The title pretty much sums it up.

I want to detect back/home button press using an Accessibility Service.

It seems that onKeyEvent is not triggered when pressing these buttons.



Solution 1:[1]

it is possible to detect key events if you create your own accessibility service. After that, you need to implement your behavior for the onKeyEvent().

Here is an example:

public class AccessibilityKeyDetector extends AccessibilityService  {

...

  @Override
    protected boolean onKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
 // Do your magic
    }

..
}

I am assuming that you have checked the accessibility permissions and set the correct configuration of your service.

I hope this code fits you. If you have more doubts, please contact me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nessie