Code example for KeyEvent

Methods: sendKeySync

0
     * Inject the key sequence to take a screenshot. 
     */ 
    private void takeScreenshot() { 
        getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN,
                KeyEvent.KEYCODE_POWER));
        getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN,
                KeyEvent.KEYCODE_VOLUME_DOWN));
        // the volume down key event will cause the 'volume adjustment' UI to appear in the 
        // foreground, and steal UI focus 
        // unfortunately this means the next key event will get directed to the 
        // 'volume adjustment' UI, instead of this test's activity 
        // for this reason this test must be signed with platform certificate, to grant this test 
        // permission to inject key events to another process 
        getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_UP,
                KeyEvent.KEYCODE_VOLUME_DOWN));
        getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_UP,
                KeyEvent.KEYCODE_POWER));
    } 
 
    /** 
     * Get the directory where screenshot images are stored.