Recipe Intercepting a Physical Key Press

A standard Android device has multiple physical keys that can trigger events, as listed in Table 5.1.

Table 5.1 The Possible Physical Keys on an Android Device

Physical Key

KeyEvent

Description

Power button

KEYCODE_POWER

Turns on the device or wakes it from sleep; brings UI to the lock screen

BACK key

KEYCODE_BACK

Navigates to the previous screen

MENU key

KEYCODE_MENU

Shows the menu for the active application

HOME key

KEYCODE_HOME

Navigates to the home screen

SEARCH key

KEYCODE_SEARCH

Launches a search in the active application

Camera button

KEYCODE_CAMERA

Launches the camera

Volume button

KEYCODE_VOLUME_UP KEYCODE_VOLUME_DOWN

Controls volume of the media by context (voice when in a phone call, music when in media playback, or ringer volume)

KEYCODE_DPAD_UP

KEYCODE_DPAD_DOWN

KEYCODE_DPAD_LEFT

KEYCODE_DPAD_RIGHT

Directional pad on some devices

Trackball

-

Directional joystick on some devices

Keyboard

KEYCODE_0, ..., KEYCODE_9, KEYCODE_A, ..., KEYCODE_Z

Pull-out keyboard on some devices

Media button

KEYCODE_HEADSETHOOK

Headset Play/Pause button

The system first sends any KeyEvent to the appropriate callback method in the in-focus activity or view. These callback methods are

■ onKeyUp(), onKeyDown(), onKeyLongPress() —Physical key press callbacks

■ onTrackballEvent(), onTouchEvent()—Trackball and touchscreen press callbacks

■ onFocusChanged()—Called when the view gains or loses focus

These can be overridden by the application to customize with different actions. For example, to turn off the camera button (to avoid accidental presses), just consume the event in the onKeyDown() callback method for the Activity. This is done by intercepting the method for the event KeyEvent.KEYCODE_CAMERA and returning true:

public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA) {

return true; // consume event, hence do nothing on camera button

return super.onKeyDown(keyCode, event);

By consuming the event, it does not get passed on to other Android components.There are a few exceptions to this:

■ The Power button and HOME key are intercepted by the system and do not reach the application for customization.

■ The BACK, MENU, HOME, and SEARCH keys should not intercept the KeyDown but instead the KeyUp.This coincides with Android 2.0 suggestions because these buttons might not be physical keys in other platforms.

Listing 5.1 shows a variety of examples of intercepting physical key presses, including the following:

■ The Camera and DPAD left buttons are intercepted in onKeyDown() to show a message to the screen, and then it is consumed (by returning true).

■ The Volume Up button is intercepted to show a message to the screen, but it is not consumed (returning false) and hence also actually increases the volume.

■ The SEARCH key is intercepted in onKeyDown(), and the startTracking() method is used to track it through to the key up where a message is sent to the screen.

■ The BACK key is intercepted in onBackPressed().

A note on the latter: An Android guideline for usability is that the BACK key should generally not be customized. However, if needed for some reason in an activity or dialog, there is a separate callback method available with Application Programming Interface (API) level 5 (Eclair) and higher to intercept the BACK key: onBackPressed().

For backward compatibility with earlier Software Development Kits (SDKs), the KeyEvent.KEYCODE_BACK can be intercepted, and the onBackPressed() method can be explicitly called for earlier SDKs, as shown in Listing 5.1. (Note, this code can only be compiled with Android 2.0 or higher due to the explicit mention of Eclair, but it is backward compatible at run-time on all devices.) To intercept the BACK key in a view (not shown here) requires using the startTracking() method, which is similar to the SEARCH key example in Listing 5.1.

Listing 5.1 src/com/cookbook/PhysicalKeyPress.java package com.cookbook.physkey; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.widget.Toast;

public class PhysicalKeyPress extends Activity {

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_CAMERA:

Toast.makeText(this, "Pressed Camera Button",

Toast.LENGTH_LONG).show(); return true; case KeyEvent.KEYCODE_DPAD_LEFT:

Toast.makeText(this, "Pressed DPAD Left Button",

Toast.LENGTH_LONG).show(); return true; case KeyEvent.KEYCODE_VOLUME_UP:

Toast.makeText(this, "Pressed Volume Up Button",

Toast.LENGTH_LONG).show(); return false; case KeyEvent.KEYCODE_SEARCH:

//example of tracking through to the KeyUp if(event.getRepeatCount() == 0)

event.startTracking(); return true; case KeyEvent.KEYCODE_BACK:

// Make new onBackPressed compatible with earlier SDK's if (android.os.Build.VERSION.SDK_INT

< android.os.Build.VERSION_CODES.ECLAIR && event.getRepeatCount() == 0) { onBackPressed();

return super.onKeyDown(keyCode, event);

public void onBackPressed() {

Toast.makeText(this, "Pressed BACK Key", Toast.LENGTH_LONG).show();

public boolean onKeyUp(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_SEARCH && event.isTracking() && !event.isCanceled()) {

Toast.makeText(this, "Pressed SEARCH Key",

Toast.LENGTH_LONG).show(); return true;

return super.onKeyUp(keyCode, event);

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Responses

  • pupetta
    How to intercept search key in android?
    7 years ago
  • Sayid
    Can android intercept physical keyboard events in a service?
    6 years ago
  • Severi
    How to intercept a keypress java android?
    4 years ago
  • shelby
    How to intercept enter key from phisycal keyboard android?
    2 months ago

Post a comment