Recipe 9.5 Capturing Hardware Buttons Programmatically

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
CaptureHardwareButtons.zip

In addition to the standard hardware buttons such as Home, MENU, Back, and Search, some Android devices have built-in keyboards and a directional pad. This recipe shows you how to programmatically capture the pressing of these buttons so that your application can override their built-in functions. For example, the default behavior of the Back button on an Android device will remove the current active activity and display the previous activity. You may want to override this behavior by capturing the Back button so that the application can perform something else (such as confirming with the user if he really wants to quit the current activity) when the Back button is pressed.

Solution

To capture the various hardware buttons on your Android device, you need to implement the onKeyDown() method in your activity, as shown in the following example:

package com.example.capturehardwarebuttons;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.