Home » Android » core » ui » Events » Android Physical Keys Example

About Chryssa Aliferi

Avatar photo
Chryssa is a Computer Science graduate from Athens University of Economic and Business. During her studies, Chryssa carried out a great variety of projects ranging from networking to software engineering. She is very keen on front end development especially on mobile technologies and web applications. She has worked as a junior Software Engineer in the telecommunications area and currently works as an Android Developer.

Android Physical Keys Example

Every Android device is provided with physical keys. In the wide variety of Android mobile devices, we may meet devices with three or four physical or virtual keys, however the default and most common pattern nowadays, are the three basic soft keys, which are the back button KEYCODE_BACK, the home button KEYCODE_HOME, and the menu button KEYCODE_MENU.

Android devices, in their vast majority, also have the VOLUME_UP and VOLUME_DOWN keys, for executing the basic sound functionality.

In this example, we are going to discuss how to catch the basic events of press and release of these keys, and how we can slightly change their basic functionality.

However, be careful each time you override the functionality of the back button action, and the functionality of all the hard buttons as well, as it is not suggested to change the Android default user experience. Android users expect certain behavior from certain buttons. This is the reason, why in the latest Android API versions, we are no more able to catch the KEYCODE_HOME key event, and the KEYCODE_MENU is only able to implement certain functionality.

You can see more about KEYCODE_MENU and menu inflating in the example Android Menu Example.

But, let’s begin with our code! For our example will use the following tools in a Windows 64-bit or an OS X platform:

  • JDK 1.7
  • Eclipse 4.2 Juno
  • Android SDK 4.4.2

Let’s take a closer look:

1. Create a New Android Application Project

You may skip project creation and jump directly to the beginning of the example below.

Open Eclipse IDE and go to File → New → Project → Android Application Project.

Figure 2. Create a new Android project

Figure 1. Create a new Android project

Specify the name of the application, the project and the package and then click Next.

Figure 2. Create a new Android project name

Figure 2. Create a new Android project name

In the next window, the “Create Activity” option should be checked. The new created activity will be the main activity of your project. Then press Next button.

Create Activity

Figure 3. Configure the project

In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so click Next.

Configure Launcher Icon

Figure 4. Configure the launcher icon

Select the “Blank Activity” option and press Next.

Blank Activity

Figure 5. Create the activity and select its type

You have to specify a name for the new Activity and a name for the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. It will also be created a fragment layout xml, that we are not going to use in this project and you can remove it if you want. Then press Finish.

Figure 6. Create a new blank activity

Figure 6. Create a new blank activity

Here you can see, how will the structure of the project become when finished:

Figure 7. The tree of the project

Figure 7. The tree of the project

2. Creating the layout of the main AndroidPhysicalKeysActivity

We are going to make a simple layout xml for the AndroidPhysicalKeysActivity.class, that consists of a LinearLayout with vertical orientation, that includes two TextViews to help us visualize the actions done, when the physical keys are pressed.

Open res/layout/activity_main.xml, go to the respective xml tab and paste the following:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:ignore="MergeRootFrame" >

        android:textAppearance="?android:attr/textAppearanceLarge" />

        android:textAppearance="?android:attr/textAppearanceLarge" />


3. Creating the source code of the main AndroidPhysicalKeysActivity Activity

Open src/com.javacodegeeks.androidphysicalkeysexample/AndroidPhysicalKeysActivity.java file and paste the code below.


package com.javacodegeeks.androidphysicalkeysexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidPhysicalKeysActivity extends Activity {

	TextView actionLabel;
	int counter = 0;

	public void onCreate(Bundle savedInstanceState) {
		actionLabel = (TextView) findViewById(R.id.action);

	// catches the onKeyDown button event
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			actionLabel.setText("KEYCODE_BACK key pressed");
			Toast.makeText(this, "Press again back for exit", Toast.LENGTH_SHORT).show();
			if (counter > 1) {
			return true;
		case KeyEvent.KEYCODE_VOLUME_UP:
			actionLabel.setText("VOLUME_UP key pressed");
			return true;
			actionLabel.setText("VOLUME_DOWN key pressed");
			return true;

		return super.onKeyDown(keyCode, event);

	// catches the onKeyUp button event
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			actionLabel.setText("KEYCODE_BACK key released");
			return true;
		case KeyEvent.KEYCODE_VOLUME_UP:
			actionLabel.setText("VOLUME_UP key released");
			return true;
			actionLabel.setText("VOLUME_DOWN key released");
			return true;
		return super.onKeyDown(keyCode, event);

	// works for API level 5 and lower
	public void onBackPressed() {
		actionLabel.setText("BACK key pressed");

	// catches the long press button event (longer than 2 seconds)
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		Toast.makeText(this, "Pressed for a long time", Toast.LENGTH_SHORT).show();
		return true;

	// catches the on touch event on screen and shows the specific pixels
	// touched
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();
		actionLabel.setText("Touch press on x: " + x + " y: " + y);
		return true;

4. Android Manifest

The AndroidManifest.xml of our project is very very simple:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >

        android:targetSdkVersion="19" />

        android:label="@string/app_name" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

5. Build, compile and run

When we build, compile and run our project, the main AndroidPhysicalKeysActivity should look like this:

Figure 8. This is how the main Activity looks like.

Figure 8. This is how the main Activity looks like.

Figure 9. This is how the main Activity looks like.

Figure 9. This is how the main Activity looks like.

Download the Eclipse Project

This was an example of Android Physical Keys.

You can download the full source code of this example here: AndroidPhysicalKeysExample

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments