Example usage for android.view KeyEvent getAction

List of usage examples for android.view KeyEvent getAction

Introduction

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

Prototype

public final int getAction() 

Source Link

Document

Retrieve the action of this key event.

Usage

From source file:com.lofland.housebot.BotController.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.housebot);//from w  ww.  jav  a  2 s .c  o  m
    Log.d(TAG, "onCreate");

    /*
     * TODO: If you need to maintain and pass around context:
     * http://stackoverflow.com/questions/987072/using-application-context-everywhere
     */

    // Display start up toast:
    // http://developer.android.com/guide/topics/ui/notifiers/toasts.html
    Context context = getApplicationContext();
    CharSequence text = "ex Nehilo!";
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, text, duration);
    // Display said toast
    toast.show();

    /*
     *  Turn on WiFi if it is off
     *  http://stackoverflow.com/questions/8863509/how-to-programmatically-turn-off-wifi-on-android-device
     */
    WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

    // Prevent keyboard from popping up as soon as app launches: (it works!)
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    /*
     * Keep the screen on, because as long as we are talking to the robot, this needs to be up http://stackoverflow.com/questions/9335908/how-to- prevent-the-screen-of
     * -an-android-device-to-turn-off-during-the-execution
     */
    this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    /*
     * One or more of these three lines sets the screen to minimum brightness, Which should extend battery drain, and be less distracting on the robot.
     */
    final WindowManager.LayoutParams winParams = this.getWindow().getAttributes();
    winParams.screenBrightness = 0.01f;
    winParams.buttonBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;

    // The "Connect" screen has a "Name" and "Address box"
    // I'm not really sure what one puts in these, and if you leave them
    // empty it works fine.
    // So not 110% sure what to do with these. Can the text just be: ""?
    // Just comment these out, and run the command with nulls?
    // mName = (EditText) findViewById(R.id.name_edit);
    // mAddress = (EditText) findViewById(R.id.address_edit);
    // The NXT Remote Control app pops up a list of seen NXTs, so maybe I
    // need to implement that instead.

    // Text to speech
    tts = new TextToSpeech(this, this);

    btnSpeak = (Button) findViewById(R.id.btnSpeak);

    txtText = (EditText) findViewById(R.id.txtSpeakText);

    // Now we need a Robot object before we an use any Roboty values!
    // We can pass defaults in or use the ones it provides
    myRobot = new Robot(INITIALTRAVELSPEED, INITIALROTATESPEED, DEFAULTVIEWANGLE);
    // We may have to pass this robot around a bit. ;)

    // Status Lines
    TextView distanceText = (TextView) findViewById(R.id.distanceText);
    distanceText.setText("???");
    TextView distanceLeftText = (TextView) findViewById(R.id.distanceLeftText);
    distanceLeftText.setText("???");
    TextView distanceRightText = (TextView) findViewById(R.id.distanceRightText);
    distanceRightText.setText("???");
    TextView headingText = (TextView) findViewById(R.id.headingText);
    headingText.setText("???");
    TextView actionText = (TextView) findViewById(R.id.isDoingText);
    actionText.setText("None");

    // Travel speed slider bar
    SeekBar travelSpeedBar = (SeekBar) findViewById(R.id.travelSpeed_seekBar);
    travelSpeedBar.setProgress(myRobot.getTravelSpeed());
    travelSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setTravelSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    // View angle slider bar
    SeekBar viewAngleBar = (SeekBar) findViewById(R.id.viewAngle_seekBar);
    viewAngleBar.setProgress(myRobot.getViewAngle());
    viewAngleBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setViewAngle(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Log.d(TAG, "View Angle Slider ");
            /*
             * If this gets sent every few milliseconds with the normal output, then there is no need to send a specific command every time it changes!
             */
            // sendCommandToRobot(Command.VIEWANGLE);
        }
    });

    // Rotation speed slider bar speedSP_seekBar
    SeekBar rotateSpeedBar = (SeekBar) findViewById(R.id.rotateSpeed_seekBar);
    rotateSpeedBar.setProgress(myRobot.getRotateSpeed());
    rotateSpeedBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            myRobot.setRotateSpeed(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    /*
     * This is where we find the four direction buttons defined So we could define ALL buttons this way, set up an ENUM with all options, and call the same function for ALL
     * options!
     * 
     * Just be sure the "release" only stops the robot on these, and not every button on the screen.
     * 
     * Maybe see how the code I stole this form does it?
     */
    Button buttonUp = (Button) findViewById(R.id.forward_button);
    buttonUp.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.FORWARD));
    Button buttonDown = (Button) findViewById(R.id.reverse_button);
    buttonDown.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.REVERSE));
    Button buttonLeft = (Button) findViewById(R.id.left_button);
    buttonLeft.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.LEFT));
    Button buttonRight = (Button) findViewById(R.id.right_button);
    buttonRight.setOnTouchListener(new DirectionButtonOnTouchListener(Direction.RIGHT));

    // button on click event
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            speakOut();
        }

    });

    /*
     * This causes the typed text to be spoken when the Enter key is pressed.
     */
    txtText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on key press
                // Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                speakOut();
                return true;
            }
            return false;
        }
    });

    // Connect button
    connectToggleButton = (ToggleButton) findViewById(R.id.connectToggleButton);
    connectToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // The toggle is enabled
                Log.d(TAG, "Connect button Toggled On!");
                myRobot.setConnectRequested(true);
            } else {
                // The toggle is disabled
                Log.d(TAG, "Connect button Toggled OFF.");
                myRobot.setConnectRequested(false);
            }
        }
    });

    if (nxtStatusMessageHandler == null)
        nxtStatusMessageHandler = new StatusMessageHandler();

    mStatusThread = new StatusThread(context, nxtStatusMessageHandler);
    mStatusThread.start();

    // Start the web service!
    Log.d(TAG, "Start web service here:");
    // Initiate message handler for web service
    if (robotWebServerMessageHandler == null)
        robotWebServerMessageHandler = new WebServerMessageHandler(this); // Has to include "this" to send context, see WebServerMessageHandler for explanation

    robotWebServer = new WebServer(context, PORT, robotWebServerMessageHandler, myRobot);

    try {
        robotWebServer.start();
    } catch (IOException e) {
        Log.d(TAG, "robotWebServer failed to start");
        //e.printStackTrace();
    }

    // TODO:
    /*
     * See this reference on how to rebuild this handler in onCreate if it is gone: http://stackoverflow.com/questions/18221593/android-handler-changing-weakreference
     */
    // TODO - Should I stop this thread in Destroy or some such place?

    Log.d(TAG, "Web service was started.");

}

From source file:org.connectbot.ConsoleActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        StrictModeSetup.run();//from w  w  w. j av a  2s . c  o m
    }

    hardKeyboard = getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY;

    clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    titleBarHide = prefs.getBoolean(PreferenceConstants.TITLEBARHIDE, false);
    if (titleBarHide && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // This is a separate method because Gradle does not uniformly respect the conditional
        // Build check. See: https://code.google.com/p/android/issues/detail?id=137195
        requestActionBar();
    }

    this.setContentView(R.layout.act_console);

    // hide status bar if requested by user
    if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    // TODO find proper way to disable volume key beep if it exists.
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // handle requested console from incoming intent
    if (icicle == null) {
        requested = getIntent().getData();
    } else {
        String uri = icicle.getString(STATE_SELECTED_URI);
        if (uri != null) {
            requested = Uri.parse(uri);
        }
    }

    inflater = LayoutInflater.from(this);

    toolbar = (Toolbar) findViewById(R.id.toolbar);

    pager = (TerminalViewPager) findViewById(R.id.console_flip);
    pager.addOnPageChangeListener(new TerminalViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            setTitle(adapter.getPageTitle(position));
            onTerminalChanged();
        }
    });
    adapter = new TerminalPagerAdapter();
    pager.setAdapter(adapter);

    empty = (TextView) findViewById(android.R.id.empty);

    stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
    stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
    stringPrompt = (EditText) 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);

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

            return true;
        }
    });

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

    booleanYes = (Button) 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();
        }
    });

    Button booleanNo = (Button) 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();
        }
    });

    fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);

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

    keyboardGroup = (LinearLayout) findViewById(R.id.keyboard_group);

    keyboardAlwaysVisible = prefs.getBoolean(PreferenceConstants.KEY_ALWAYS_VISIVLE, false);
    if (keyboardAlwaysVisible) {
        // equivalent to android:layout_above=keyboard_group
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.addRule(RelativeLayout.ABOVE, R.id.keyboard_group);
        pager.setLayoutParams(layoutParams);

        // Show virtual keyboard
        keyboardGroup.setVisibility(View.VISIBLE);
    }

    mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
    mKeyboardButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View terminal = adapter.getCurrentTerminalView();
            if (terminal == null)
                return;
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInputFromWindow(terminal.getApplicationWindowToken(),
                    InputMethodManager.SHOW_FORCED, 0);
            terminal.requestFocus();
            hideEmulatedKeys();
        }
    });

    findViewById(R.id.button_ctrl).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_esc).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_tab).setOnClickListener(emulatedKeysListener);

    addKeyRepeater(findViewById(R.id.button_up));
    addKeyRepeater(findViewById(R.id.button_up));
    addKeyRepeater(findViewById(R.id.button_down));
    addKeyRepeater(findViewById(R.id.button_left));
    addKeyRepeater(findViewById(R.id.button_right));

    findViewById(R.id.button_home).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_end).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_pgup).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_pgdn).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f1).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f2).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f3).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f4).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f5).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f6).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f7).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f8).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f9).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f10).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f11).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f12).setOnClickListener(emulatedKeysListener);

    actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        if (titleBarHide) {
            actionBar.hide();
        }
        actionBar.addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
            public void onMenuVisibilityChanged(boolean isVisible) {
                inActionBarMenu = isVisible;
                if (!isVisible) {
                    hideEmulatedKeys();
                }
            }
        });
    }

    final HorizontalScrollView keyboardScroll = (HorizontalScrollView) findViewById(R.id.keyboard_hscroll);
    if (!hardKeyboard) {
        // Show virtual keyboard and scroll back and forth
        showEmulatedKeys(false);
        keyboardScroll.postDelayed(new Runnable() {
            @Override
            public void run() {
                final int xscroll = findViewById(R.id.button_f12).getRight();
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "smoothScrollBy(toEnd[" + xscroll + "])");
                }
                keyboardScroll.smoothScrollBy(xscroll, 0);
                keyboardScroll.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (BuildConfig.DEBUG) {
                            Log.d(TAG, "smoothScrollBy(toStart[" + (-xscroll) + "])");
                        }
                        keyboardScroll.smoothScrollBy(-xscroll, 0);
                    }
                }, 500);
            }
        }, 500);
    }

    // Reset keyboard auto-hide timer when scrolling
    keyboardScroll.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                autoHideEmulatedKeys();
                break;
            case MotionEvent.ACTION_UP:
                v.performClick();
                return (true);
            }
            return (false);
        }
    });

    tabs = (TabLayout) findViewById(R.id.tabs);
    if (tabs != null)
        setupTabLayoutWithViewPager();

    pager.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showEmulatedKeys(true);
        }
    });

    // Change keyboard button image according to soft keyboard visibility
    // How to detect keyboard visibility: http://stackoverflow.com/q/4745988
    contentView = findViewById(android.R.id.content);
    contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            contentView.getWindowVisibleDisplayFrame(r);
            int screenHeight = contentView.getRootView().getHeight();
            int keypadHeight = screenHeight - r.bottom;

            if (keypadHeight > screenHeight * 0.15) {
                // keyboard is opened
                mKeyboardButton.setImageResource(R.drawable.ic_keyboard_hide);
                mKeyboardButton.setContentDescription(
                        getResources().getText(R.string.image_description_hide_keyboard));
            } else {
                // keyboard is closed
                mKeyboardButton.setImageResource(R.drawable.ic_keyboard);
                mKeyboardButton.setContentDescription(
                        getResources().getText(R.string.image_description_show_keyboard));
            }
        }
    });
}

From source file:com.actionbarsherlock.internal.ActionBarSherlockCompat.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (DEBUG)//from  w w w  .  jav a2s . com
        Log.d(TAG, "[dispatchKeyEvent] event: " + event);

    final int keyCode = event.getKeyCode();

    // Not handled by the view hierarchy, does the action bar want it
    // to cancel out of something special?
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        final int action = event.getAction();
        // Back cancels action modes first.
        if (mActionMode != null) {
            if (action == KeyEvent.ACTION_UP) {
                mActionMode.finish();
            }
            if (DEBUG)
                Log.d(TAG, "[dispatchKeyEvent] returning true");
            return true;
        }

        // Next collapse any expanded action views.
        if (wActionBar != null && wActionBar.hasExpandedActionView()) {
            if (action == KeyEvent.ACTION_UP) {
                wActionBar.collapseActionView();
            }
            if (DEBUG)
                Log.d(TAG, "[dispatchKeyEvent] returning true");
            return true;
        }
    }

    boolean result = false;
    if (keyCode == KeyEvent.KEYCODE_MENU && isReservingOverflow()) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.isLongPress()) {
            mMenuKeyIsLongPress = true;
        } else if (event.getAction() == KeyEvent.ACTION_UP) {
            if (!mMenuKeyIsLongPress) {
                if (mActionMode == null && wActionBar != null) {
                    if (wActionBar.isOverflowMenuShowing()) {
                        wActionBar.hideOverflowMenu();
                    } else {
                        wActionBar.showOverflowMenu();
                    }
                }
                result = true;
            }
            mMenuKeyIsLongPress = false;
        }
    }

    if (DEBUG)
        Log.d(TAG, "[dispatchKeyEvent] returning " + result);
    return result;
}

From source file:com.android.mail.ui.ConversationListFragment.java

@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
    if (view instanceof SwipeableListView) {
        SwipeableListView list = (SwipeableListView) view;
        // Don't need to handle ENTER because it's auto-handled as a "click".
        if (KeyboardUtils.isKeycodeDirectionEnd(keyCode, ViewUtils.isViewRtl(list))) {
            if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                if (mKeyInitiatedFromList) {
                    int currentPos = list.getSelectedItemPosition();
                    if (currentPos < 0) {
                        // Find the activated item if the focused item is non-existent.
                        // This can happen when the user transitions from touch mode.
                        currentPos = list.getCheckedItemPosition();
                    }//from  w  ww .  j  av  a  2  s  .  c  om
                    if (currentPos >= 0) {
                        // We don't use onListItemSelected because right arrow should always
                        // view the conversation even in CAB/no_sender_image mode.
                        viewConversation(currentPos);
                        commitDestructiveActions(
                                Utils.useTabletUI(mActivity.getActivityContext().getResources()));
                    }
                }
                mKeyInitiatedFromList = false;
            } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                mKeyInitiatedFromList = true;
            }
            return true;
        } else if ((keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
                && keyEvent.getAction() == KeyEvent.ACTION_UP) {
            final int position = list.getSelectedItemPosition();
            if (position >= 0) {
                final Object item = getAnimatedAdapter().getItem(position);
                if (item != null && item instanceof ConversationCursor) {
                    final Conversation conv = ((ConversationCursor) item).getConversation();
                    mCallbacks.onConversationFocused(conv);
                }
            }
        }
    }
    return false;
}

From source file:com.devwang.logcabin.LogCabinMainActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    //    //from   w  w w .  j  a  va  2  s .co  m
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

        if ((System.currentTimeMillis() - exitTime) > 2000) // System.currentTimeMillis()2000
        {
            Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            if (mChatService != null)
                mChatService.stop();
            finish();
            System.exit(0);
        }

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

void onMediaButtonEvent(KeyEvent ev) {
    if (ev.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK) {
        if (ev.getAction() == KeyEvent.ACTION_UP) {
            if (currentState == STATE_WAITING_INCOMING) {
                acceptIncomingCall();/*from www.  j a va2 s.  c  om*/
            } else {
                setMicMute(!isMicMute());
                for (StateListener l : stateListeners)
                    l.onAudioSettingsChanged();
            }
        }
    }
}

From source file:org.brandroid.openmanager.fragments.ContentFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.content_layout, container, false);
    mGrid = (GridView) v.findViewById(R.id.content_grid);
    final OpenFragment me = this;
    mGrid.setOnKeyListener(new OnKeyListener() {
        @Override//from   www . j a v a2s  . com
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() != KeyEvent.ACTION_DOWN)
                return false;
            int col = 0;
            int cols = 1;
            try {
                if (!OpenExplorer.BEFORE_HONEYCOMB) {
                    Method m = GridView.class.getMethod("getNumColumns", new Class[0]);
                    Object tmp = m.invoke(mGrid, new Object[0]);
                    if (tmp instanceof Integer) {
                        cols = (Integer) tmp;
                        col = mGrid.getSelectedItemPosition() % cols;
                    }
                }
            } catch (Exception e) {
            }
            Logger.LogDebug("ContentFragment.mGrid.onKey(" + keyCode + "," + event + ")@" + col);
            if (!OpenExplorer.BEFORE_HONEYCOMB)
                cols = (Integer) mGrid.getNumColumns();
            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && col == 0)
                return onFragmentDPAD(me, false);
            else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && col == cols - 1)
                return onFragmentDPAD(me, true);
            else if (MenuUtils.getMenuShortcut(event) != null) {
                MenuItem item = MenuUtils.getMenuShortcut(event);
                if (onOptionsItemSelected(item)) {
                    Toast.makeText(v.getContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
            return false;
        }
    });
    v.setOnLongClickListener(this);
    mGrid.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            getMenuInflater().inflate(R.menu.context_file, menu);
            onPrepareOptionsMenu(menu);
        }
    });
    //if(mProgressBarLoading == null)
    //   mProgressBarLoading = v.findViewById(R.id.content_progress);
    setProgressVisibility(false);
    super.onCreateView(inflater, container, savedInstanceState);
    //v.setBackgroundResource(R.color.lightgray);

    /*
    if (savedInstanceState != null && savedInstanceState.containsKey("location")) {
       String location = savedInstanceState.getString("location");
       if(location != null && !location.equals("") && location.startsWith("/"))
       {
    Logger.LogDebug("Content location restoring to " + location);
    mPath = new OpenFile(location);
    mData = getManager().getChildren(mPath);
    updateData(mData);
       }
       //setContentPath(path, false);
    }
    */

    return v;
}

From source file:de.danoeh.antennapod.core.cast.CastManager.java

/**
 * Clients can call this method to delegate handling of the volume. Clients should override
 * {@code dispatchEvent} and call this method:
 * <pre>/*from   w  ww. j  a v  a 2 s  . c o m*/
 public boolean dispatchKeyEvent(KeyEvent event) {
 if (mCastManager.onDispatchVolumeKeyEvent(event, VOLUME_DELTA)) {
 return true;
 }
 return super.dispatchKeyEvent(event);
 }
 * </pre>
 * @param event The dispatched event.
 * @param volumeDelta The amount by which volume should be increased or decreased in each step
 * @return <code>true</code> if volume is handled by the library, <code>false</code> otherwise.
 */
public boolean onDispatchVolumeKeyEvent(KeyEvent event, double volumeDelta) {
    if (isConnected()) {
        boolean isKeyDown = event.getAction() == KeyEvent.ACTION_DOWN;
        switch (event.getKeyCode()) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            return changeVolume(volumeDelta, isKeyDown);
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            return changeVolume(-volumeDelta, isKeyDown);
        }
    }
    return false;
}

From source file:dev.ukanth.ufirewall.MainActivity.java

@Override
public boolean onKeyUp(final int keyCode, final KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_UP) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_MENU:
            if (mainMenu != null) {
                mainMenu.performIdentifierAction(R.id.menu_list_item, 0);
                return true;
            }/*from w ww.j ava  2s  .  co  m*/
            break;
        case KeyEvent.KEYCODE_BACK:
            if (isDirty()) {
                new MaterialDialog.Builder(this).title(R.string.confirmation).cancelable(false)
                        .content(R.string.unsaved_changes_message).positiveText(R.string.apply)
                        .negativeText(R.string.discard).callback(new MaterialDialog.ButtonCallback() {
                            @Override
                            public void onPositive(MaterialDialog dialog) {
                                applyOrSaveRules();
                                dialog.dismiss();
                            }

                            @Override
                            public void onNegative(MaterialDialog dialog) {
                                setDirty(false);
                                Api.applications = null;
                                finish();
                                System.exit(0);
                                //force reload rules.
                                MainActivity.super.onKeyDown(keyCode, event);
                                dialog.dismiss();
                            }
                        }).show();
                return true;

            } else {
                setDirty(false);
                finish();
                System.exit(0);
            }

        }
    }
    return super.onKeyUp(keyCode, event);
}

From source file:org.appcelerator.titanium.TiBaseActivity.java

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    boolean handled = false;

    TiViewProxy window;//from www.  ja va 2 s .  co m
    if (this.window != null) {
        window = this.window;
    } else {
        window = this.view;
    }

    if (window == null) {
        return super.dispatchKeyEvent(event);
    }

    switch (event.getKeyCode()) {
    case KeyEvent.KEYCODE_BACK: {

        if (event.getAction() == KeyEvent.ACTION_UP) {
            String backEvent = "android:back";
            KrollProxy proxy = null;
            //android:back could be fired from a tabGroup window (activityProxy)
            //or hw window (window).This event is added specifically to the activity
            //proxy of a tab group in window.js
            if (activityProxy.hasListeners(backEvent)) {
                proxy = activityProxy;
            } else if (window.hasListeners(backEvent)) {
                proxy = window;
            }

            if (proxy != null) {
                proxy.fireEvent(backEvent, null);
                handled = true;
            }

        }
        break;
    }
    case KeyEvent.KEYCODE_CAMERA: {
        if (window.hasListeners(TiC.EVENT_ANDROID_CAMERA)) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent(TiC.EVENT_ANDROID_CAMERA, null);
            }
            handled = true;
        }
        // TODO: Deprecate old event
        if (window.hasListeners("android:camera")) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent("android:camera", null);
            }
            handled = true;
        }

        break;
    }
    case KeyEvent.KEYCODE_FOCUS: {
        if (window.hasListeners(TiC.EVENT_ANDROID_FOCUS)) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent(TiC.EVENT_ANDROID_FOCUS, null);
            }
            handled = true;
        }
        // TODO: Deprecate old event
        if (window.hasListeners("android:focus")) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent("android:focus", null);
            }
            handled = true;
        }

        break;
    }
    case KeyEvent.KEYCODE_SEARCH: {
        if (window.hasListeners(TiC.EVENT_ANDROID_SEARCH)) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent(TiC.EVENT_ANDROID_SEARCH, null);
            }
            handled = true;
        }
        // TODO: Deprecate old event
        if (window.hasListeners("android:search")) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent("android:search", null);
            }
            handled = true;
        }

        break;
    }
    case KeyEvent.KEYCODE_VOLUME_UP: {
        if (window.hasListeners(TiC.EVENT_ANDROID_VOLUP)) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent(TiC.EVENT_ANDROID_VOLUP, null);
            }
            handled = true;
        }
        // TODO: Deprecate old event
        if (window.hasListeners("android:volup")) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent("android:volup", null);
            }
            handled = true;
        }

        break;
    }
    case KeyEvent.KEYCODE_VOLUME_DOWN: {
        if (window.hasListeners(TiC.EVENT_ANDROID_VOLDOWN)) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent(TiC.EVENT_ANDROID_VOLDOWN, null);
            }
            handled = true;
        }
        // TODO: Deprecate old event
        if (window.hasListeners("android:voldown")) {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                window.fireEvent("android:voldown", null);
            }
            handled = true;
        }

        break;
    }
    }

    if (!handled) {
        handled = super.dispatchKeyEvent(event);
    }

    return handled;
}