Recipe 9.5 Capturing Hardware Buttons Programmatically
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, ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access