Example usage for android.view KeyEvent getDeviceId

List of usage examples for android.view KeyEvent getDeviceId

Introduction

In this page you can find the example usage for android.view KeyEvent getDeviceId.

Prototype

@Override
public final int getDeviceId() 

Source Link

Usage

From source file:com.mobiletin.inputmethod.indic.LatinIME.java

@Override
public boolean onKeyUp(final int keyCode, final KeyEvent keyEvent) {
    mSpecialKeyDetector.onKeyUp(keyEvent);
    if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) {
        return super.onKeyUp(keyCode, keyEvent);
    }/*from  w w  w.j av a  2  s  . c  om*/
    final long keyIdentifier = keyEvent.getDeviceId() << 32 + keyEvent.getKeyCode();
    if (mInputLogic.mCurrentlyPressedHardwareKeys.remove(keyIdentifier)) {
        return true;
    }
    return super.onKeyUp(keyCode, keyEvent);
}

From source file:com.mobiletin.inputmethod.indic.LatinIME.java

@Override
public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) {
    mSpecialKeyDetector.onKeyDown(keyEvent);
    if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) {
        return super.onKeyDown(keyCode, keyEvent);
    }/*w w w .j a  va  2s.  co m*/
    final Event event = getHardwareKeyEventDecoder(keyEvent.getDeviceId()).decodeHardwareKey(keyEvent);
    // If the event is not handled by LatinIME, we just pass it to the parent implementation.
    // If it's handled, we return true because we did handle it.
    if (event.isHandled()) {
        mInputLogic.onCodeInput(mSettings.getCurrent(), event, mKeyboardSwitcher.getKeyboardShiftMode(),
                // TODO: this is not necessarily correct for a hardware keyboard right now
                mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler);
        return true;
    }
    return super.onKeyDown(keyCode, keyEvent);
}

From source file:com.yek.keyboard.anysoftkeyboard.AnySoftKeyboard.java

@Override
public boolean onKeyDown(final int keyEventKeyCode, @NonNull KeyEvent event) {
    InputConnection ic = getCurrentInputConnection();
    if (handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition, mGlobalCursorPosition))
        return true;
    final boolean shouldTranslateSpecialKeys = isInputViewShown();

    //greater than zero means it is a physical keyboard.
    //we also want to hide the view if it's a glyph (for example, not physical volume-up key)
    if (event.getDeviceId() > 0 && event.isPrintingKey())
        onPhysicalKeyboardKeyPressed();/*from w  w  w .  java  2  s.  c  om*/

    mHardKeyboardAction.initializeAction(event, mMetaState);

    switch (keyEventKeyCode) {
    /****
     * SPECIAL translated HW keys If you add new keys here, do not forget
     * to add to the
     */
    case KeyEvent.KEYCODE_CAMERA:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleBackWord(getCurrentInputConnection());
            return true;
        }
        // DO NOT DELAY CAMERA KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_FOCUS:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleDeleteLastCharacter(false);
            return true;
        }
        // DO NOT DELAY FOCUS KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
            return true;
        }
        // DO NOT DELAY VOLUME UP KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_RIGHT);
            return true;
        }
        // DO NOT DELAY VOLUME DOWN KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    /****
     * END of SPECIAL translated HW keys code section
     */
    case KeyEvent.KEYCODE_BACK:
        if (event.getRepeatCount() == 0 && getInputView() != null) {
            if (getInputView().handleBack()) {
                // consuming the meta keys
                if (ic != null) {
                    // translated, so we also take care of the metakeys
                    ic.clearMetaKeyStates(Integer.MAX_VALUE);
                }
                mMetaState = 0;
                return true;
            }
        }
        break;
    case 0x000000cc:// API 14: KeyEvent.KEYCODE_LANGUAGE_SWITCH
        switchToNextPhysicalKeyboard(ic);
        return true;
    case KeyEvent.KEYCODE_SHIFT_LEFT:
    case KeyEvent.KEYCODE_SHIFT_RIGHT:
        if (event.isAltPressed() && Workarounds.isAltSpaceLangSwitchNotPossible()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE: letting it fall-through to the other meta-keys
    case KeyEvent.KEYCODE_ALT_LEFT:
    case KeyEvent.KEYCODE_ALT_RIGHT:
    case KeyEvent.KEYCODE_SYM:
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown before handle"));
        mMetaState = MyMetaKeyKeyListener.handleKeyDown(mMetaState, keyEventKeyCode, event);
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after handle"));
        break;
    case KeyEvent.KEYCODE_SPACE:
        if ((event.isAltPressed() && !Workarounds.isAltSpaceLangSwitchNotPossible())
                || event.isShiftPressed()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE:
        // letting it fall through to the "default"
    default:

        // Fix issue 185, check if we should process key repeat
        if (!mAskPrefs.getUseRepeatingKeys() && event.getRepeatCount() > 0)
            return true;

        AnyKeyboard.HardKeyboardTranslator keyTranslator = (AnyKeyboard.HardKeyboardTranslator) getCurrentAlphabetKeyboard();
        if (getKeyboardSwitcher().isCurrentKeyboardPhysical() && keyTranslator != null) {
            // sometimes, the physical keyboard will delete input, and then add some.
            // we'll try to make it nice.
            if (ic != null)
                ic.beginBatchEdit();
            try {
                // issue 393, backword on the hw keyboard!
                if (mAskPrefs.useBackword() && keyEventKeyCode == KeyEvent.KEYCODE_DEL
                        && event.isShiftPressed()) {
                    handleBackWord(ic);
                    return true;
                } else {
                    // http://article.gmane.org/gmane.comp.handhelds.openmoko.android-freerunner/629
                    keyTranslator.translatePhysicalCharacter(mHardKeyboardAction, this);

                    if (mHardKeyboardAction.getKeyCodeWasChanged()) {
                        final int translatedChar = mHardKeyboardAction.getKeyCode();
                        // typing my own.
                        onKey(translatedChar, null, -1, new int[] { translatedChar }, true/*faking from UI*/);
                        // my handling we are at a regular key press, so we'll update
                        // our meta-state member
                        mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
                        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust - translated"));
                        return true;
                    }
                }
            } finally {
                if (ic != null)
                    ic.endBatchEdit();
            }
        }
        if (event.isPrintingKey()) {
            // we are at a regular key press, so we'll update our
            // meta-state
            // member
            mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
            Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust"));
        }
    }
    return super.onKeyDown(keyEventKeyCode, event);
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

@Override
public boolean onKeyDown(final int keyEventKeyCode, @NonNull KeyEvent event) {
    InputConnection ic = getCurrentInputConnection();
    if (handleSelectionExpending(keyEventKeyCode, ic, mGlobalSelectionStartPosition, mGlobalCursorPosition))
        return true;
    final boolean shouldTranslateSpecialKeys = isInputViewShown();

    //greater than zero means it is a physical keyboard.
    //we also want to hide the view if it's a glyph (for example, not physical volume-up key)
    if (event.getDeviceId() > 0 && event.isPrintingKey())
        onPhysicalKeyboardKeyPressed();/*w  w w .  ja v a  2s .c om*/

    mHardKeyboardAction.initializeAction(event, mMetaState);

    switch (keyEventKeyCode) {
    /****
     * SPECIAL translated HW keys If you add new keys here, do not forget
     * to add to the
     */
    case KeyEvent.KEYCODE_CAMERA:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleBackWord(getCurrentInputConnection());
            return true;
        }
        // DO NOT DELAY CAMERA KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_FOCUS:
        if (shouldTranslateSpecialKeys && mAskPrefs.useCameraKeyForBackspaceBackword()) {
            handleDeleteLastCharacter(false);
            return true;
        }
        // DO NOT DELAY FOCUS KEY with unneeded checks in default mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_LEFT);
            return true;
        }
        // DO NOT DELAY VOLUME UP KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (shouldTranslateSpecialKeys && mAskPrefs.useVolumeKeyForLeftRight()) {
            sendDownUpKeyEvents(KeyEvent.KEYCODE_DPAD_RIGHT);
            return true;
        }
        // DO NOT DELAY VOLUME DOWN KEY with unneeded checks in default
        // mark
        return super.onKeyDown(keyEventKeyCode, event);
    /****
     * END of SPECIAL translated HW keys code section
     */
    case KeyEvent.KEYCODE_BACK:
        if (event.getRepeatCount() == 0 && getInputView() != null) {
            if (getInputView().handleBack()) {
                // consuming the meta keys
                if (ic != null) {
                    // translated, so we also take care of the metakeys
                    ic.clearMetaKeyStates(Integer.MAX_VALUE);
                }
                mMetaState = 0;
                return true;
            }
        }
        break;
    case 0x000000cc:// API 14: KeyEvent.KEYCODE_LANGUAGE_SWITCH
        switchToNextPhysicalKeyboard(ic);
        return true;
    case KeyEvent.KEYCODE_SHIFT_LEFT:
    case KeyEvent.KEYCODE_SHIFT_RIGHT:
        if (event.isAltPressed() && Workarounds.isAltSpaceLangSwitchNotPossible()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE: letting it fall-through to the other meta-keys
    case KeyEvent.KEYCODE_ALT_LEFT:
    case KeyEvent.KEYCODE_ALT_RIGHT:
    case KeyEvent.KEYCODE_SYM:
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown before handle"));
        mMetaState = MyMetaKeyKeyListener.handleKeyDown(mMetaState, keyEventKeyCode, event);
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after handle"));
        break;
    case KeyEvent.KEYCODE_SPACE:
        if ((event.isAltPressed() && !Workarounds.isAltSpaceLangSwitchNotPossible())
                || event.isShiftPressed()) {
            switchToNextPhysicalKeyboard(ic);
            return true;
        }
        // NOTE:
        // letting it fall through to the "default"
    default:

        // Fix issue 185, check if we should process key repeat
        if (!mAskPrefs.getUseRepeatingKeys() && event.getRepeatCount() > 0)
            return true;

        HardKeyboardTranslator keyTranslator = (HardKeyboardTranslator) getCurrentAlphabetKeyboard();
        if (getKeyboardSwitcher().isCurrentKeyboardPhysical() && keyTranslator != null) {
            // sometimes, the physical keyboard will delete input, and then add some.
            // we'll try to make it nice.
            if (ic != null)
                ic.beginBatchEdit();
            try {
                // issue 393, backword on the hw keyboard!
                if (mAskPrefs.useBackword() && keyEventKeyCode == KeyEvent.KEYCODE_DEL
                        && event.isShiftPressed()) {
                    handleBackWord(ic);
                    return true;
                } else {
                    // http://article.gmane.org/gmane.comp.handhelds.openmoko.android-freerunner/629
                    keyTranslator.translatePhysicalCharacter(mHardKeyboardAction, this);

                    if (mHardKeyboardAction.getKeyCodeWasChanged()) {
                        final int translatedChar = mHardKeyboardAction.getKeyCode();
                        // typing my own.
                        onKey(translatedChar, null, -1, new int[] { translatedChar }, true/*faking from UI*/);
                        // my handling we are at a regular key press, so we'll update
                        // our meta-state member
                        mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
                        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust - translated"));
                        return true;
                    }
                }
            } finally {
                if (ic != null)
                    ic.endBatchEdit();
            }
        }
        if (event.isPrintingKey()) {
            // we are at a regular key press, so we'll update our
            // meta-state
            // member
            mMetaState = MyMetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
            Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyDown after adjust"));
        }
    }
    return super.onKeyDown(keyEventKeyCode, event);
}

From source file:com.anysoftkeyboard.AnySoftKeyboard.java

@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
    Logger.d(TAG, "onKeyUp keycode=%d", keyCode);
    switch (keyCode) {
    // Issue 248/* w  w  w .  j a  v a 2 s . co m*/
    case KeyEvent.KEYCODE_VOLUME_DOWN:
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (!isInputViewShown()) {
            return super.onKeyUp(keyCode, event);
        }
        if (mAskPrefs.useVolumeKeyForLeftRight()) {
            // no need of vol up/down sound
            return true;
        }
    case KeyEvent.KEYCODE_DPAD_DOWN:
    case KeyEvent.KEYCODE_DPAD_UP:
    case KeyEvent.KEYCODE_DPAD_LEFT:
    case KeyEvent.KEYCODE_DPAD_RIGHT:
        if (getInputView() != null && getInputView().isShown() && getInputView().isShifted()) {
            event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(),
                    event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(),
                    KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
            InputConnection ic = getCurrentInputConnection();
            if (ic != null)
                ic.sendKeyEvent(event);

            return true;
        }
        break;
    case KeyEvent.KEYCODE_ALT_LEFT:
    case KeyEvent.KEYCODE_ALT_RIGHT:
    case KeyEvent.KEYCODE_SHIFT_LEFT:
    case KeyEvent.KEYCODE_SHIFT_RIGHT:
    case KeyEvent.KEYCODE_SYM:
        mMetaState = MyMetaKeyKeyListener.handleKeyUp(mMetaState, keyCode, event);
        Logger.d(TAG + "-meta-key", getMetaKeysStates("onKeyUp"));
        setInputConnectionMetaStateAsCurrentMetaKeyKeyListenerState();
        break;
    }
    return super.onKeyUp(keyCode, event);
}

From source file:org.pocketworkstation.pckeyboard.LatinIME.java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_DPAD_DOWN:
    case KeyEvent.KEYCODE_DPAD_UP:
    case KeyEvent.KEYCODE_DPAD_LEFT:
    case KeyEvent.KEYCODE_DPAD_RIGHT:
        LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
        // Enable shift key and DPAD to do selections
        if (inputView != null && inputView.isShown() && inputView.getShiftState() == Keyboard.SHIFT_ON) {
            event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(),
                    event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(),
                    KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
            InputConnection ic = getCurrentInputConnection();
            if (ic != null)
                ic.sendKeyEvent(event);/*from  w  w w  . j a va  2  s.  c  om*/
            return true;
        }
        break;
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (!mVolUpAction.equals("none") && isKeyboardVisible()) {
            return doSwipeAction(mVolUpAction);
        }
        break;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (!mVolDownAction.equals("none") && isKeyboardVisible()) {
            return doSwipeAction(mVolDownAction);
        }
        break;
    }
    return super.onKeyUp(keyCode, event);
}

From source file:org.distantshoresmedia.keyboard.LatinIME.java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_DPAD_DOWN:
    case KeyEvent.KEYCODE_DPAD_UP:
    case KeyEvent.KEYCODE_DPAD_LEFT:
    case KeyEvent.KEYCODE_DPAD_RIGHT:
        // If tutorial is visible, don't allow dpad to work
        if (mTutorial != null) {
            return true;
        }//from   ww  w.j ava2 s. c  o m
        TKKeyboardView inputView = mKeyboardSwitcher.getInputView();
        // Enable shift key and DPAD to do selections
        if (inputView != null && inputView.isShown() && inputView.getShiftState() == Keyboard.SHIFT_ON) {
            event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(),
                    event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(),
                    KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
            InputConnection ic = getCurrentInputConnection();
            if (ic != null)
                ic.sendKeyEvent(event);
            return true;
        }
        break;
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (!mVolUpAction.equals("none") && isKeyboardVisible()) {
            return doSwipeAction(mVolUpAction);
        }
        break;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (!mVolDownAction.equals("none") && isKeyboardVisible()) {
            return doSwipeAction(mVolDownAction);
        }
        break;
    }
    return super.onKeyUp(keyCode, event);
}

From source file:android.support.v7.app.AppCompatDelegateImplV7.java

private boolean preparePanel(PanelFeatureState st, KeyEvent event) {
    if (isDestroyed()) {
        return false;
    }// w  w  w  . ja  v a2  s . c o  m

    // Already prepared (isPrepared will be reset to false later)
    if (st.isPrepared) {
        return true;
    }

    if ((mPreparedPanel != null) && (mPreparedPanel != st)) {
        // Another Panel is prepared and possibly open, so close it
        closePanel(mPreparedPanel, false);
    }

    final Window.Callback cb = getWindowCallback();

    if (cb != null) {
        st.createdPanelView = cb.onCreatePanelView(st.featureId);
    }

    final boolean isActionBarMenu = (st.featureId == FEATURE_OPTIONS_PANEL
            || st.featureId == FEATURE_ACTION_BAR);

    if (isActionBarMenu && mDecorContentParent != null) {
        // Enforce ordering guarantees around events so that the action bar never
        // dispatches menu-related events before the panel is prepared.
        mDecorContentParent.setMenuPrepared();
    }

    if (st.createdPanelView == null) {
        // Init the panel state's menu--return false if init failed
        if (st.menu == null || st.refreshMenuContent) {
            if (st.menu == null) {
                if (!initializePanelMenu(st) || (st.menu == null)) {
                    return false;
                }
            }

            if (isActionBarMenu && mDecorContentParent != null) {
                if (mActionMenuPresenterCallback == null) {
                    mActionMenuPresenterCallback = new ActionMenuPresenterCallback();
                }
                mDecorContentParent.setMenu(st.menu, mActionMenuPresenterCallback);
            }

            // Creating the panel menu will involve a lot of manipulation;
            // don't dispatch change events to presenters until we're done.
            st.menu.stopDispatchingItemsChanged();
            if (!cb.onCreatePanelMenu(st.featureId, st.menu)) {
                // Ditch the menu created above
                st.setMenu(null);

                if (isActionBarMenu && mDecorContentParent != null) {
                    // Don't show it in the action bar either
                    mDecorContentParent.setMenu(null, mActionMenuPresenterCallback);
                }

                return false;
            }

            st.refreshMenuContent = false;
        }

        // Preparing the panel menu can involve a lot of manipulation;
        // don't dispatch change events to presenters until we're done.
        st.menu.stopDispatchingItemsChanged();

        // Restore action view state before we prepare. This gives apps
        // an opportunity to override frozen/restored state in onPrepare.
        if (st.frozenActionViewState != null) {
            st.menu.restoreActionViewStates(st.frozenActionViewState);
            st.frozenActionViewState = null;
        }

        // Callback and return if the callback does not want to show the menu
        if (!cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) {
            if (isActionBarMenu && mDecorContentParent != null) {
                // The app didn't want to show the menu for now but it still exists.
                // Clear it out of the action bar.
                mDecorContentParent.setMenu(null, mActionMenuPresenterCallback);
            }
            st.menu.startDispatchingItemsChanged();
            return false;
        }

        // Set the proper keymap
        KeyCharacterMap kmap = KeyCharacterMap
                .load(event != null ? event.getDeviceId() : KeyCharacterMap.VIRTUAL_KEYBOARD);
        st.qwertyMode = kmap.getKeyboardType() != KeyCharacterMap.NUMERIC;
        st.menu.setQwertyMode(st.qwertyMode);
        st.menu.startDispatchingItemsChanged();
    }

    // Set other state
    st.isPrepared = true;
    st.isHandled = false;
    mPreparedPanel = st;

    return true;
}

From source file:android.support.v7ox.app.AppCompatDelegateImplV7.java

private boolean preparePanel(PanelFeatureState st, KeyEvent event) {
    if (isDestroyed()) {
        return false;
    }// w  w w . j av a 2s . c  om

    // Already prepared (isPrepared will be reset to false later)
    if (st.isPrepared) {
        return true;
    }

    if ((mPreparedPanel != null) && (mPreparedPanel != st)) {
        // Another Panel is prepared and possibly open, so close it
        closePanel(mPreparedPanel, false);
    }

    final Window.Callback cb = getWindowCallback();

    if (cb != null) {
        st.createdPanelView = cb.onCreatePanelView(st.featureId);
    }

    final boolean isActionBarMenu = (st.featureId == FEATURE_OPTIONS_PANEL
            || st.featureId == FEATURE_SUPPORT_ACTION_BAR);

    if (isActionBarMenu && mDecorContentParent != null) {
        // Enforce ordering guarantees around events so that the action bar never
        // dispatches menu-related events before the panel is prepared.
        mDecorContentParent.setMenuPrepared();
    }

    if (st.createdPanelView == null
            && (!isActionBarMenu || !(peekSupportActionBar() instanceof ToolbarActionBar))) {
        // Since ToolbarActionBar handles the list options menu itself, we only want to
        // init this menu panel if we're not using a TAB.
        if (st.menu == null || st.refreshMenuContent) {
            if (st.menu == null) {
                if (!initializePanelMenu(st) || (st.menu == null)) {
                    return false;
                }
            }

            if (isActionBarMenu && mDecorContentParent != null) {
                if (mActionMenuPresenterCallback == null) {
                    mActionMenuPresenterCallback = new ActionMenuPresenterCallback();
                }
                mDecorContentParent.setMenu(st.menu, mActionMenuPresenterCallback);
            }

            // Creating the panel menu will involve a lot of manipulation;
            // don't dispatch change events to presenters until we're done.
            st.menu.stopDispatchingItemsChanged();
            if (!cb.onCreatePanelMenu(st.featureId, st.menu)) {
                // Ditch the menu created above
                st.setMenu(null);

                if (isActionBarMenu && mDecorContentParent != null) {
                    // Don't show it in the action bar either
                    mDecorContentParent.setMenu(null, mActionMenuPresenterCallback);
                }

                return false;
            }

            st.refreshMenuContent = false;
        }

        // Preparing the panel menu can involve a lot of manipulation;
        // don't dispatch change events to presenters until we're done.
        st.menu.stopDispatchingItemsChanged();

        // Restore action view state before we prepare. This gives apps
        // an opportunity to override frozen/restored state in onPrepare.
        if (st.frozenActionViewState != null) {
            st.menu.restoreActionViewStates(st.frozenActionViewState);
            st.frozenActionViewState = null;
        }

        // Callback and return if the callback does not want to show the menu
        if (!cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) {
            if (isActionBarMenu && mDecorContentParent != null) {
                // The app didn't want to show the menu for now but it still exists.
                // Clear it out of the action bar.
                mDecorContentParent.setMenu(null, mActionMenuPresenterCallback);
            }
            st.menu.startDispatchingItemsChanged();
            return false;
        }

        // Set the proper keymap
        KeyCharacterMap kmap = KeyCharacterMap
                .load(event != null ? event.getDeviceId() : KeyCharacterMap.VIRTUAL_KEYBOARD);
        st.qwertyMode = kmap.getKeyboardType() != KeyCharacterMap.NUMERIC;
        st.menu.setQwertyMode(st.qwertyMode);
        st.menu.startDispatchingItemsChanged();
    }

    // Set other state
    st.isPrepared = true;
    st.isHandled = false;
    mPreparedPanel = st;

    return true;
}

From source file:jmri.enginedriver.throttle.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    boolean isExternal = false;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        InputDevice idev = getDevice(event.getDeviceId());
        if (idev != null && idev.toString() != null && idev.toString().contains("Location: external"))
            isExternal = true;/*  w  w  w .  ja v a 2s . c  o  m*/
    }

    if (isExternal) { // if has come from the phone itself, don't try to process it here
        if (!whichGamePadMode.equals(WHICH_GAMEPAD_MODE_NONE)) { // respond to the gamepad and keyboard inputs only if the preference is set

            boolean acceptEvent = true; // default to assuming that we will respond to the event

            int action = event.getAction();
            int keyCode = event.getKeyCode();
            int repeatCnt = event.getRepeatCount();
            int whichThrottle;
            int whichGamePadIsEventFrom = findWhichGamePadEventIsFrom(event.getDeviceId(), event.getKeyCode());

            if ((whichGamePadIsEventFrom > -1) && (whichGamePadIsEventFrom < gamePadDeviceIdsTested.length)) { // the event came from a gamepad
                if (gamePadDeviceIdsTested[getGamePadIndexFromThrottleNo(
                        whichGamePadIsEventFrom)] != GAMEPAD_GOOD) { //if not, testing for this gamepad is not complete or has failed
                    acceptEvent = false;
                }
            } else {
                acceptEvent = false;
            }

            if (acceptEvent) {
                if ((usingMultiplePads) && (whichGamePadIsEventFrom >= -1)) { // we have multiple gamepads AND the preference is set to make use of them AND the event came for a gamepad
                    if (whichGamePadIsEventFrom >= 0) {
                        whichThrottle = whichGamePadIsEventFrom;
                    } else {
                        GamepadFeedbackSound(true);
                        return (true);
                    }
                } else {
                    whichThrottle = whichVolume; // work out which throttle the volume keys are currently set to contol... and use that one
                }

                boolean isActive = getConsist(whichThrottle).isActive();

                if (keyCode != 0) {
                    Log.d("Engine_Driver", "keycode " + keyCode + " action " + action + " repeat " + repeatCnt);
                }

                if (action == ACTION_UP) {
                    mGamepadAutoIncrement = false;
                    mGamepadAutoDecrement = false;
                    GamepadFeedbackSoundStop();
                }

                if (keyCode == gamePadKeys[2]) { // DPAD Up Button
                    performButtonAction(5, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[3]) { // DPAD Down Button
                    performButtonAction(7, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[4]) { // DPAD Left Button
                    performButtonAction(8, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[5]) { // DPAD Right Button
                    performButtonAction(6, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[7]) { // ios button
                    performButtonAction(1, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys_Up[8]) { // X button
                    performButtonAction(3, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys_Up[9]) { // Triangle button
                    performButtonAction(2, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys_Up[10]) { // @ button
                    performButtonAction(4, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[6]) { // start button
                    performButtonAction(0, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[11]) { // Left Shoulder button
                    performButtonAction(10, action, isActive, whichThrottle, whichGamePadIsEventFrom,
                            repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[12]) { // Left Shoulder button
                    performButtonAction(11, action, isActive, whichThrottle, whichGamePadIsEventFrom,
                            repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[13]) { // Left Shoulder button
                    performButtonAction(12, action, isActive, whichThrottle, whichGamePadIsEventFrom,
                            repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[14]) { // Left Shoulder button
                    performButtonAction(13, action, isActive, whichThrottle, whichGamePadIsEventFrom,
                            repeatCnt);
                    return (true); // stop processing this key

                } else if (keyCode == gamePadKeys[1]) { // Return button
                    // NextThrottle
                    /* if ((action == ACTION_DOWN) && (repeatCnt == 0)) {
                        if (usingMultiplePads && whichGamePadIsEventFrom >= 0) {
                    whichGamePadIsEventFrom = swapToNextAvilableThrottleForGamePad(whichGamePadIsEventFrom, false);
                        } else {
                    setNextActiveThrottle(true);
                        }
                    } */
                    performButtonAction(9, action, isActive, whichThrottle, whichGamePadIsEventFrom, repeatCnt);
                    return (true); // stop processing this key
                }
            } else { // event is from a gamepad that has not finished testing. Ignore it
                return (true); // stop processing this key
            }
            //  for now pass all keystrokes not in gamePadKeys[] to super
            //  if problems occur, we can uncomment the next 2 lines
            //            else if (!((keyCode == KEYCODE_BACK) || (keyCode == KEYCODE_VOLUME_DOWN) || (keyCode == KEYCODE_VOLUME_UP) || (keyCode == KEYCODE_MENU)))
            //            return (true); // swallow all other keystrokes except back, menu and the volume keys
        }
    } else if (IS_ESU_MCII) {
        // Process ESU MCII keys
        int action = event.getAction();
        int keyCode = event.getKeyCode();
        int repeatCnt = event.getRepeatCount();
        boolean isActive = getConsist(whichVolume).isActive();

        if (keyCode != 0) {
            Log.d("Engine_Driver",
                    "ESU_MCII: keycode " + keyCode + " action " + action + " repeat " + repeatCnt);
            if (action == ACTION_UP) {
                esuButtonAutoIncrement = false;
                esuButtonAutoDecrement = false;
            }

            switch (keyCode) {
            case MobileControl2.KEYCODE_TOP_LEFT:
            case MobileControl2.KEYCODE_BOTTOM_LEFT:
            case MobileControl2.KEYCODE_TOP_RIGHT:
            case MobileControl2.KEYCODE_BOTTOM_RIGHT:
                performEsuMc2ButtonAction(keyCode, action, isActive, whichVolume, repeatCnt);
                return true; // stop processing this key
            default:
                // Unrecognised key - do nothing
                Log.d("Engine_Driver", "ESU_MCII: Unrecognised keyCode: " + keyCode);

            }
        }
    }
    return super.dispatchKeyEvent(event);
}