Example usage for android.view KeyEvent ACTION_UP

List of usage examples for android.view KeyEvent ACTION_UP

Introduction

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

Prototype

int ACTION_UP

To view the source code for android.view KeyEvent ACTION_UP.

Click Source Link

Document

#getAction value: the key has been released.

Usage

From source file:org.telegram.ui.ActionBar.ActionBarLayout.java

@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
    if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK
            && event.getAction() == KeyEvent.ACTION_UP) {
        return delegate != null && delegate.onPreIme() || super.dispatchKeyEventPreIme(event);
    }/*w ww .  j a va2s  . c o m*/
    return super.dispatchKeyEventPreIme(event);
}

From source file:android.webkit.AccessibilityInjector.java

/**
 * Attempts to handle key events when accessibility is turned on.
 *
 * @param event The key event to handle.
 * @return {@code true} if the event was handled.
 *//*from w  w w .j a  va2s . co  m*/
public boolean handleKeyEventIfNecessary(KeyEvent event) {
    if (!isAccessibilityEnabled()) {
        mAccessibilityScriptInjected = false;
        toggleFallbackAccessibilityInjector(false);
        return false;
    }

    if (mAccessibilityScriptInjected) {
        // if an accessibility script is injected we delegate to it the key
        // handling. this script is a screen reader which is a fully fledged
        // solution for blind users to navigate in and interact with web
        // pages.
        if (event.getAction() == KeyEvent.ACTION_UP) {
            mWebViewClassic.sendBatchableInputMessage(EventHub.KEY_UP, 0, 0, event);
        } else if (event.getAction() == KeyEvent.ACTION_DOWN) {
            mWebViewClassic.sendBatchableInputMessage(EventHub.KEY_DOWN, 0, 0, event);
        } else {
            return false;
        }

        return true;
    }

    if (mAccessibilityInjectorFallback != null) {
        // if an accessibility injector is present (no JavaScript enabled or
        // the site opts out injecting our JavaScript screen reader) we let
        // it decide whether to act on and consume the event.
        return mAccessibilityInjectorFallback.onKeyEvent(event);
    }

    return false;
}

From source file:com.app.blockydemo.ui.ScriptActivity.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    //Dismiss ActionMode without effecting checked items

    FormulaEditorVariableListFragment formulaEditorVariableListFragment = (FormulaEditorVariableListFragment) getSupportFragmentManager()
            .findFragmentByTag(FormulaEditorVariableListFragment.VARIABLE_TAG);

    if (formulaEditorVariableListFragment != null) {
        if (formulaEditorVariableListFragment.isVisible()) {
            ListAdapter adapter = formulaEditorVariableListFragment.getListAdapter();
            ((ScriptActivityAdapterInterface) adapter).clearCheckedItems();
            return super.dispatchKeyEvent(event);
        }/*from w  w w  .j a  v a2  s  . c  om*/
    }

    if (currentFragment != null && currentFragment.getActionModeActive()) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            ListAdapter adapter = null;
            if (currentFragment instanceof ScriptFragment) {
                adapter = ((ScriptFragment) currentFragment).getAdapter();
            } else {
                adapter = currentFragment.getListAdapter();
            }
            ((ScriptActivityAdapterInterface) adapter).clearCheckedItems();
        }
    }

    return super.dispatchKeyEvent(event);
}

From source file:org.chromium.chrome.browser.widget.findinpage.FindToolbar.java

@Override
public void onFinishInflate() {
    super.onFinishInflate();

    setOrientation(HORIZONTAL);/*from  w  w w .j  a va2  s  .  co m*/
    setGravity(Gravity.CENTER_VERTICAL);

    mFindQuery = (FindQuery) findViewById(R.id.find_query);
    mFindQuery.setFindToolbar(this);
    mFindQuery.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER);
    mFindQuery.setSelectAllOnFocus(true);
    mFindQuery.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            mAccessibilityDidActivateResult = false;
            if (!hasFocus) {
                if (mFindQuery.getText().length() > 0) {
                    mSearchKeyShouldTriggerSearch = true;
                }
                UiUtils.hideKeyboard(mFindQuery);
            }
        }
    });
    mFindQuery.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mFindInPageBridge == null)
                return;

            mAccessibilityDidActivateResult = false;
            setPrevNextEnabled(s.length() > 0);

            if (mSettingFindTextProgrammatically)
                return;

            // If we're called during onRestoreInstanceState() the current
            // view won't have been set yet. TODO(husky): Find a better fix.
            assert mCurrentTab != null;
            assert mCurrentTab.getContentViewCore() != null;
            if (mCurrentTab.getContentViewCore() == null)
                return;

            if (s.length() > 0) {
                // Don't clearResults() as that would cause flicker.
                // Just wait until onFindResultReceived updates it.
                mSearchKeyShouldTriggerSearch = false;
                mFindInPageBridge.startFinding(s.toString(), true, false);
            } else {
                clearResults();
                mFindInPageBridge.stopFinding(true);
            }

            if (!mCurrentTab.isIncognito()) {
                mLastUserSearch = s.toString();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    mFindQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (event != null && event.getAction() == KeyEvent.ACTION_UP)
                return false;

            if (mFindInPageBridge == null)
                return false;

            // Only trigger a new find if the text was set programmatically.
            // Otherwise just revisit the current active match.
            if (mSearchKeyShouldTriggerSearch) {
                mSearchKeyShouldTriggerSearch = false;
                hideKeyboardAndStartFinding(true);
            } else {
                UiUtils.hideKeyboard(mFindQuery);
                mFindInPageBridge.activateFindInPageResultForAccessibility();
                mAccessibilityDidActivateResult = true;
            }
            return true;
        }
    });

    mFindStatus = (TextView) findViewById(R.id.find_status);

    mFindPrevButton = (TintedImageButton) findViewById(R.id.find_prev_button);
    mFindPrevButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            hideKeyboardAndStartFinding(false);
        }
    });

    mFindNextButton = (TintedImageButton) findViewById(R.id.find_next_button);
    mFindNextButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            hideKeyboardAndStartFinding(true);
        }
    });

    setPrevNextEnabled(false);

    mCloseFindButton = (TintedImageButton) findViewById(R.id.close_find_button);
    mCloseFindButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            deactivate();
        }
    });
}

From source file:com.darly.im.ui.CCPActivityBase.java

/**
 *
 * @param keyCode/*  w ww .  java  2s . com*/
 * @param event
 * @return
 */
public boolean onKeyUp(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_MENU && event.getAction() == KeyEvent.ACTION_UP) {
        /*if(mOverFlowAction != null && mOverFlowAction.isEnabled()) {
           callMenuCallback(mOverFlowMenuItem, mOverFlowAction);
           return true;
        }*/
    }
    return false;
}

From source file:org.connectbot.ConsoleFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.frg_console, container, false);

    this.inflater = inflater;

    flip = (ViewFlipper) v.findViewById(R.id.console_flip);
    empty = (TextView) v.findViewById(android.R.id.empty);

    stringPromptGroup = (RelativeLayout) v.findViewById(R.id.console_password_group);
    stringPromptInstructions = (TextView) v.findViewById(R.id.console_password_instructions);
    stringPrompt = (EditText) v.findViewById(R.id.console_password);
    stringPrompt.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP)
                return false;
            if (keyCode != KeyEvent.KEYCODE_ENTER)
                return false;

            // pass collected password down to current terminal
            String value = stringPrompt.getText().toString();

            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return false;
            helper.setResponse(value);//  ww w  .j av a  2  s.c o  m

            // finally clear password for next user
            stringPrompt.setText("");
            updatePromptVisible();

            return true;
        }
    });

    booleanPromptGroup = (RelativeLayout) v.findViewById(R.id.console_boolean_group);
    booleanPrompt = (TextView) v.findViewById(R.id.console_prompt);

    booleanYes = (Button) v.findViewById(R.id.console_prompt_yes);
    booleanYes.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.TRUE);
            updatePromptVisible();
        }
    });

    booleanNo = (Button) v.findViewById(R.id.console_prompt_no);
    booleanNo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.FALSE);
            updatePromptVisible();
        }
    });

    // preload animations for terminal switching
    slide_left_in = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_in);
    slide_left_out = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_left_out);
    slide_right_in = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_right_in);
    slide_right_out = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_right_out);

    fade_out_delayed = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out_delayed);
    fade_stay_hidden = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_stay_hidden);

    // Preload animation for keyboard button
    keyboard_fade_in = AnimationUtils.loadAnimation(getActivity(), R.anim.keyboard_fade_in);
    keyboard_fade_out = AnimationUtils.loadAnimation(getActivity(), R.anim.keyboard_fade_out);

    inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

    final RelativeLayout keyboardGroup = (RelativeLayout) v.findViewById(R.id.keyboard_group);

    mKeyboardButton = (ImageView) v.findViewById(R.id.button_keyboard);
    mKeyboardButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;

            inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView ctrlButton = (ImageView) v.findViewById(R.id.button_ctrl);
    ctrlButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;
            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.metaPress(TerminalKeyListener.META_CTRL_ON);

            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView escButton = (ImageView) v.findViewById(R.id.button_esc);
    escButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;
            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.sendEscape();

            keyboardGroup.setVisibility(View.GONE);
        }
    });

    // detect fling gestures to switch between terminals
    final GestureDetector detect = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
        private float totalY = 0;

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            final float distx = e2.getRawX() - e1.getRawX();
            final float disty = e2.getRawY() - e1.getRawY();
            final int goalwidth = flip.getWidth() / 2;

            // need to slide across half of display to trigger console change
            // make sure user kept a steady hand horizontally
            if (Math.abs(disty) < (flip.getHeight() / 4)) {
                if (distx > goalwidth) {
                    shiftCurrentTerminal(SHIFT_RIGHT);
                    return true;
                }

                if (distx < -goalwidth) {
                    shiftCurrentTerminal(SHIFT_LEFT);
                    return true;
                }

            }

            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            // if copying, then ignore
            if (copySource != null && copySource.isSelectingForCopy())
                return false;

            if (e1 == null || e2 == null)
                return false;

            // if releasing then reset total scroll
            if (e2.getAction() == MotionEvent.ACTION_UP) {
                totalY = 0;
            }

            // activate consider if within x tolerance
            if (Math.abs(e1.getX() - e2.getX()) < ViewConfiguration.getTouchSlop() * 4) {

                View flip = findCurrentView(R.id.console_flip);
                if (flip == null)
                    return false;
                TerminalView terminal = (TerminalView) flip;

                // estimate how many rows we have scrolled through
                // accumulate distance that doesn't trigger immediate scroll
                totalY += distanceY;
                final int moved = (int) (totalY / terminal.bridge.charHeight);

                // consume as scrollback only if towards right half of screen
                if (e2.getX() > flip.getWidth() / 2) {
                    if (moved != 0) {
                        int base = terminal.bridge.buffer.getWindowBase();
                        terminal.bridge.buffer.setWindowBase(base + moved);
                        totalY = 0;
                        return true;
                    }
                } else {
                    // otherwise consume as pgup/pgdown for every 5 lines
                    if (moved > 5) {
                        ((vt320) terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0);
                        terminal.bridge.tryKeyVibrate();
                        totalY = 0;
                        return true;
                    } else if (moved < -5) {
                        ((vt320) terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_UP, ' ', 0);
                        terminal.bridge.tryKeyVibrate();
                        totalY = 0;
                        return true;
                    }

                }

            }

            return false;
        }

    });

    flip.setLongClickable(true);
    flip.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {

            // when copying, highlight the area
            if (copySource != null && copySource.isSelectingForCopy()) {
                int row = (int) Math.floor(event.getY() / copySource.charHeight);
                int col = (int) Math.floor(event.getX() / copySource.charWidth);

                SelectionArea area = copySource.getSelectionArea();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // recording starting area
                    if (area.isSelectingOrigin()) {
                        area.setRow(row);
                        area.setColumn(col);
                        lastTouchRow = row;
                        lastTouchCol = col;
                        copySource.redraw();
                    }
                    return true;
                case MotionEvent.ACTION_MOVE:
                    /* ignore when user hasn't moved since last time so
                     * we can fine-tune with directional pad
                     */
                    if (row == lastTouchRow && col == lastTouchCol)
                        return true;

                    // if the user moves, start the selection for other corner
                    area.finishSelectingOrigin();

                    // update selected area
                    area.setRow(row);
                    area.setColumn(col);
                    lastTouchRow = row;
                    lastTouchCol = col;
                    copySource.redraw();
                    return true;
                case MotionEvent.ACTION_UP:
                    /* If they didn't move their finger, maybe they meant to
                     * select the rest of the text with the directional pad.
                     */
                    if (area.getLeft() == area.getRight() && area.getTop() == area.getBottom()) {
                        return true;
                    }

                    // copy selected area to clipboard
                    String copiedText = area.copyFrom(copySource.buffer);

                    clipboard.setText(copiedText);
                    Toast.makeText(getActivity(), getString(R.string.console_copy_done, copiedText.length()),
                            Toast.LENGTH_LONG).show();
                    // fall through to clear state

                case MotionEvent.ACTION_CANCEL:
                    // make sure we clear any highlighted area
                    area.reset();
                    copySource.setSelectingForCopy(false);
                    copySource.redraw();
                    return true;
                }
            }

            Configuration config = getResources().getConfiguration();

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                lastX = event.getX();
                lastY = event.getY();
            } else if (event.getAction() == MotionEvent.ACTION_UP && keyboardGroup.getVisibility() == View.GONE
                    && event.getEventTime() - event.getDownTime() < CLICK_TIME
                    && Math.abs(event.getX() - lastX) < MAX_CLICK_DISTANCE
                    && Math.abs(event.getY() - lastY) < MAX_CLICK_DISTANCE) {
                keyboardGroup.startAnimation(keyboard_fade_in);
                keyboardGroup.setVisibility(View.VISIBLE);

                mUIHandler.postDelayed(new Runnable() {
                    public void run() {
                        if (keyboardGroup.getVisibility() == View.GONE)
                            return;

                        keyboardGroup.startAnimation(keyboard_fade_out);
                        keyboardGroup.setVisibility(View.GONE);
                    }
                }, KEYBOARD_DISPLAY_TIME);
            }

            // pass any touch events back to detector
            return detect.onTouchEvent(event);
        }

    });

    return v;
}

From source file:org.kde.kdeconnect.Plugins.RemoteKeyboardPlugin.RemoteKeyboardPlugin.java

private boolean handleSpecialKey(int key, boolean shift, boolean ctrl, boolean alt) {
    int keyEvent = specialKeyMap.get(key, 0);
    if (keyEvent == 0)
        return false;
    InputConnection inputConn = RemoteKeyboardService.instance.getCurrentInputConnection();
    //        Log.d("RemoteKeyboardPlugin", "Handling special key " + key + " translated to " + keyEvent + " shift=" + shift + " ctrl=" + ctrl + " alt=" + alt);

    // special sequences:
    if (ctrl && (keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT)) {
        // Ctrl + right -> next word
        ExtractedText extractedText = inputConn.getExtractedText(new ExtractedTextRequest(), 0);
        int pos = getCharPos(extractedText, ' ', keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT);
        if (pos == -1)
            pos = currentTextLength(extractedText);
        else//from  www.ja va 2  s. com
            pos++;
        int startPos = pos;
        int endPos = pos;
        if (shift) { // Shift -> select word (otherwise jump)
            Pair<Integer, Integer> sel = currentSelection(extractedText);
            int cursor = currentCursorPos(extractedText);
            //                Log.d("RemoteKeyboardPlugin", "Selection (to right): " + sel.first + " / " + sel.second + " cursor: " + cursor);
            startPos = cursor;
            if (sel.first < cursor || // active selection from left to right -> grow
                    sel.first > sel.second) // active selection from right to left -> shrink
                startPos = sel.first;
        }
        inputConn.setSelection(startPos, endPos);
    } else if (ctrl && keyEvent == KeyEvent.KEYCODE_DPAD_LEFT) {
        // Ctrl + left -> previous word
        ExtractedText extractedText = inputConn.getExtractedText(new ExtractedTextRequest(), 0);
        int pos = getCharPos(extractedText, ' ', keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT);
        if (pos == -1)
            pos = 0;
        else
            pos++;
        int startPos = pos;
        int endPos = pos;
        if (shift) {
            Pair<Integer, Integer> sel = currentSelection(extractedText);
            int cursor = currentCursorPos(extractedText);
            //                Log.d("RemoteKeyboardPlugin", "Selection (to left): " + sel.first + " / " + sel.second + " cursor: " + cursor);
            startPos = cursor;
            if (cursor < sel.first || // active selection from right to left -> grow
                    sel.first < sel.second) // active selection from right to left -> shrink
                startPos = sel.first;
        }
        inputConn.setSelection(startPos, endPos);
    } else if (shift && (keyEvent == KeyEvent.KEYCODE_DPAD_LEFT || keyEvent == KeyEvent.KEYCODE_DPAD_RIGHT
            || keyEvent == KeyEvent.KEYCODE_DPAD_UP || keyEvent == KeyEvent.KEYCODE_DPAD_DOWN
            || keyEvent == KeyEvent.KEYCODE_MOVE_HOME || keyEvent == KeyEvent.KEYCODE_MOVE_END)) {
        // Shift + up/down/left/right/home/end
        long now = SystemClock.uptimeMillis();
        inputConn.sendKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0));
        inputConn.sendKeyEvent(
                new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyEvent, 0, KeyEvent.META_SHIFT_LEFT_ON));
        inputConn.sendKeyEvent(
                new KeyEvent(now, now, KeyEvent.ACTION_UP, keyEvent, 0, KeyEvent.META_SHIFT_LEFT_ON));
        inputConn.sendKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0));
    } else if (keyEvent == KeyEvent.KEYCODE_NUMPAD_ENTER || keyEvent == KeyEvent.KEYCODE_ENTER) {
        // Enter key
        EditorInfo editorInfo = RemoteKeyboardService.instance.getCurrentInputEditorInfo();
        //            Log.d("RemoteKeyboardPlugin", "Enter: " + editorInfo.imeOptions);
        if (editorInfo != null
                && (((editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) == 0) || ctrl)) { // Ctrl+Return overrides IME_FLAG_NO_ENTER_ACTION (FIXME: make configurable?)
            // check for special DONE/GO/etc actions first:
            int[] actions = { EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_NEXT, EditorInfo.IME_ACTION_SEND,
                    EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE }; // note: DONE should be last or we might hide the ime instead of "go"
            for (int i = 0; i < actions.length; i++) {
                if ((editorInfo.imeOptions & actions[i]) == actions[i]) {
                    //                        Log.d("RemoteKeyboardPlugin", "Enter-action: " + actions[i]);
                    inputConn.performEditorAction(actions[i]);
                    return true;
                }
            }
        } else {
            // else: fall back to regular Enter-event:
            //                Log.d("RemoteKeyboardPlugin", "Enter: normal keypress");
            inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEvent));
            inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEvent));
        }
    } else {
        // default handling:
        inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEvent));
        inputConn.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEvent));
    }

    return true;
}

From source file:github.popeen.dsub.util.Notifications.java

private static void setupViews(RemoteViews rv, Context context, MusicDirectory.Entry song, boolean expanded,
        boolean playing, boolean remote, boolean isSingleFile, boolean shouldFastForward) {
    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();
    String arist = song.getArtist();
    String album = song.getAlbum();

    // Set the album art.
    try {/*from  w  ww .j  a va2 s  .c  om*/
        ImageLoader imageLoader = SubsonicActivity.getStaticImageLoader(context);
        Bitmap bitmap = null;
        if (imageLoader != null) {
            bitmap = imageLoader.getCachedImage(context, song, false);
        }
        if (bitmap == null) {
            // set default album art
            rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
        } else {
            imageLoader.setNowPlayingSmall(bitmap);
            rv.setImageViewBitmap(R.id.notification_image, bitmap);
        }
    } catch (Exception x) {
        Log.w(TAG, "Failed to get notification cover art", x);
        rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
    }

    // set the text for the notifications
    rv.setTextViewText(R.id.notification_title, title);
    rv.setTextViewText(R.id.notification_artist, arist);
    rv.setTextViewText(R.id.notification_album, album);

    boolean persistent = Util.getPreferences(context)
            .getBoolean(Constants.PREFERENCES_KEY_PERSISTENT_NOTIFICATION, false);
    if (persistent) {
        if (expanded) {
            rv.setImageViewResource(R.id.control_pause,
                    playing ? R.drawable.notification_pause : R.drawable.notification_start);

            if (shouldFastForward) {
                rv.setImageViewResource(R.id.control_previous, R.drawable.notification_rewind);
                rv.setImageViewResource(R.id.control_next, R.drawable.notification_fastforward);
            } else {
                rv.setImageViewResource(R.id.control_previous, R.drawable.notification_backward);
                rv.setImageViewResource(R.id.control_next, R.drawable.notification_forward);
            }
        } else {
            rv.setImageViewResource(R.id.control_previous,
                    playing ? R.drawable.notification_pause : R.drawable.notification_start);
            if (shouldFastForward) {
                rv.setImageViewResource(R.id.control_pause, R.drawable.notification_fastforward);
            } else {
                rv.setImageViewResource(R.id.control_pause, R.drawable.notification_forward);
            }
            rv.setImageViewResource(R.id.control_next, R.drawable.notification_close);
        }
    } else if (shouldFastForward) {
        rv.setImageViewResource(R.id.control_previous, R.drawable.notification_rewind);
        rv.setImageViewResource(R.id.control_next, R.drawable.notification_fastforward);
    } else {
        // Necessary for switching back since it appears to re-use the same layout
        rv.setImageViewResource(R.id.control_previous, R.drawable.notification_backward);
        rv.setImageViewResource(R.id.control_next, R.drawable.notification_forward);
    }

    // Create actions for media buttons

    int previous = 0, pause = 0, next = 0, close = 0, rewind = 0, fastForward = 0;
    if (expanded) {
        pause = R.id.control_pause;

        if (shouldFastForward) {
            rewind = R.id.control_previous;
            fastForward = R.id.control_next;
        } else {
            previous = R.id.control_previous;
            next = R.id.control_next;
        }

        if (remote || persistent) {
            close = R.id.notification_close;
            rv.setViewVisibility(close, View.VISIBLE);
        }
    } else {
        if (persistent) {
            pause = R.id.control_previous;
            if (shouldFastForward) {
                fastForward = R.id.control_pause;
            } else {
                next = R.id.control_pause;
            }
            close = R.id.control_next;
        } else {
            if (shouldFastForward) {
                rewind = R.id.control_previous;
                fastForward = R.id.control_next;
            } else {
                previous = R.id.control_previous;
                next = R.id.control_next;
            }

            pause = R.id.control_pause;
        }
    }

    if (isSingleFile) {
        if (previous > 0) {
            rv.setViewVisibility(previous, View.GONE);
            previous = 0;
        }
        if (rewind > 0) {
            rv.setViewVisibility(rewind, View.GONE);
            rewind = 0;
        }

        if (next > 0) {
            rv.setViewVisibility(next, View.GONE);
            next = 0;
        }

        if (fastForward > 0) {
            rv.setViewVisibility(fastForward, View.GONE);
            fastForward = 0;
        }
    }

    PendingIntent pendingIntent;
    if (previous > 0) {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_PREVIOUS");
        prevIntent.setComponent(new ComponentName(context, DownloadService.class));

        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(previous, pendingIntent);
    }
    if (rewind > 0) {
        Intent rewindIntent = new Intent("KEYCODE_MEDIA_REWIND");
        rewindIntent.setComponent(new ComponentName(context, DownloadService.class));
        rewindIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_REWIND));
        pendingIntent = PendingIntent.getService(context, 0, rewindIntent, 0);
        rv.setOnClickPendingIntent(rewind, pendingIntent);
    }
    if (pause > 0) {
        if (playing) {
            Intent pauseIntent = new Intent("KEYCODE_MEDIA_PLAY_PAUSE");
            pauseIntent.setComponent(new ComponentName(context, DownloadService.class));

            pauseIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                    new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
            pendingIntent = PendingIntent.getService(context, 0, pauseIntent, 0);
            rv.setOnClickPendingIntent(pause, pendingIntent);
        } else {
            Intent prevIntent = new Intent("KEYCODE_MEDIA_START");
            prevIntent.setComponent(new ComponentName(context, DownloadService.class));

            prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                    new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY));
            pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
            rv.setOnClickPendingIntent(pause, pendingIntent);
        }
    }
    if (next > 0) {
        Intent nextIntent = new Intent("KEYCODE_MEDIA_NEXT");
        nextIntent.setComponent(new ComponentName(context, DownloadService.class));

        nextIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT));
        pendingIntent = PendingIntent.getService(context, 0, nextIntent, 0);
        rv.setOnClickPendingIntent(next, pendingIntent);
    }
    if (fastForward > 0) {
        Intent fastForwardIntent = new Intent("KEYCODE_MEDIA_FAST_FORWARD");
        fastForwardIntent.setComponent(new ComponentName(context, DownloadService.class));
        fastForwardIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD));
        pendingIntent = PendingIntent.getService(context, 0, fastForwardIntent, 0);
        rv.setOnClickPendingIntent(fastForward, pendingIntent);
    }
    if (close > 0) {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_STOP");
        prevIntent.setComponent(new ComponentName(context, DownloadService.class));

        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_STOP));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(close, pendingIntent);
    }
}

From source file:org.kde.kdeconnect.UserInterface.DeviceFragment.java

@Override
public void onResume() {
    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();/*from  ww w  .j  ava  2  s .com*/
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                boolean fromDeviceList = getArguments().getBoolean("fromDeviceList", false);
                // Handle back button so we go to the list of devices in case we came from there
                if (fromDeviceList) {
                    mActivity.onDeviceSelected(null);
                    return true;
                }
            }
            return false;
        }
    });
}

From source file:com.stasbar.knowyourself.alarms.AlarmActivity.java

@Override
public boolean dispatchKeyEvent(@NonNull KeyEvent keyEvent) {
    // Do this in dispatch to intercept a few of the system keys.
    LOGGER.v("dispatchKeyEvent: %s", keyEvent);

    switch (keyEvent.getKeyCode()) {
    // Volume keys and camera keys dismiss the alarm.
    case KeyEvent.KEYCODE_POWER:
    case KeyEvent.KEYCODE_VOLUME_UP:
    case KeyEvent.KEYCODE_VOLUME_DOWN:
    case KeyEvent.KEYCODE_VOLUME_MUTE:
    case KeyEvent.KEYCODE_HEADSETHOOK:
    case KeyEvent.KEYCODE_CAMERA:
    case KeyEvent.KEYCODE_FOCUS:
        if (!mAlarmHandled && keyEvent.getAction() == KeyEvent.ACTION_UP) {
            switch (mVolumeBehavior) {
            case SettingsActivity.VOLUME_BEHAVIOR_SNOOZE:
                snooze();/*from  w  ww . ja v a2 s  . co  m*/
                break;
            case SettingsActivity.VOLUME_BEHAVIOR_DISMISS:
                dismiss();
                break;
            default:
                break;
            }
        }
        return true;
    default:
        return super.dispatchKeyEvent(keyEvent);
    }
}