Search code examples
javaandroidappium

Long press a custom physical button on android device with appium java


I have a an custom-made phone in which it has a specific SOS button that I need to long press.

I am trying to do key press like this.

   driver.longPressKey(new KeyEvent( AndroidKey.HOME) );

which is working but Custom key code 287. How do I send that? I tried something like this

driver.longPressKey(new KeyEvent( AndroidKey.valueOf("287")) );

but this gives an enum error

Version: java-client: 7.5.1


Solution

  • Error Reason

    AndroidKey is Enum and valueOf method works like:

    AndroidKey.valueOf("HOME");
    

    while the HOME is defined in Enum.

    public enum AndroidKey {
        UNKNOWN(0),
        ...
        HOME(3),
        ...
    

    Press Custom Key Code

    Key Code 287 is not present in AndroidKey Enum.

    But KeyEvent constructor requires it.

    For this case I suggest to make a custom KeyEvent child class.

    import com.google.common.collect.ImmutableMap
    import io.appium.java_client.android.nativekey.KeyEvent
    
    import static java.util.Optional.ofNullable
    
    class MyKeyEvent extends KeyEvent {
    
        private int keyCode;
    
        public MyKeyEvent(int keyCode) {
            this.keyCode = keyCode;
        }
    
        @Override
        public Map<String, Object> build() {
            final ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
            final int keyCode = ofNullable(this.keyCode)
                    .orElseThrow(() -> new IllegalStateException("The key code must be set"));
            builder.put("keycode", keyCode);
            return builder.build();
        }
    }
    

    and for the long press:

    driver.longPressKey(new MyKeyEvent(287));
    

    Disclaimer

    As I see this might work (since the Appium command executor will get the valid structure for long-press command), but I haven't the ability to run this code on some device or emulator. And I don't know the driver behavior once it'll try to execute some unknown key code.

    So, let me know if it doesn't work, and I'll try to improve/fix.