Robot keys to simulate Home button press on iOS using Java

I’m using this method here to simulate the hardware “HOME” button press (CMD+SHIFT+H) on an iOS device.

public static void homeButtonPress(AppiumDriver mobileDriver){
try{
Robot robot = new Robot();
robot.setAutoDelay(300);
robot.keyPress(KeyEvent.VK_META);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_META);
}catch(Exception e) {
e.printStackTrace();
}
}

When I actually launch the appium server and run the code, finder opens the java application and code exits with no error. The home button isn’t simulated either. Any thoughts on this?

This code snippet works for me:

        Robot robot = new Robot();
        robot.setAutoDelay(300);
        // Use Apple script to get focus on the simulator
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("AppleScript");
        String script = "tell application \"Simulator\" \n activate \n end tell";
        engine.eval(script);
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_SHIFT);
        robot.keyPress(KeyEvent.VK_H);
       // Have to release the key press
        robot.keyRelease(KeyEvent.VK_H);
        robot.keyRelease(KeyEvent.VK_H);
        robot.keyRelease(KeyEvent.VK_SHIFT);

There are 2 things you need to be aware of here:

  1. You have to get focus on the simulator before you press on the combination of SHIFT + OPTION + H. Otherwise robot java program ( which is launched separately) will get the focus
  2. Have to release the pressed keys

Does the same thing work for hardware key press as well?

Please see my answer for “launching the home screen in is simulator” here http://stackoverflow.com/questions/43233505/with-appium-how-to-click-the-home-button-or-launch-the-home-screen-in-ios-simu/43371922#43371922