Overwrite the Volume buttons functionality

Objective: In this tutorial you will learn about “How to overwrite the default functionality of Volume keys which is to increase or decrease the volume of phone .

We will create a simple functionality, say a Counter, When you press volume up, the counter will increase and vice versa.

How to achieve this???

We have a method called

onKeyDown(int keyCode, KeyEvent event)

in KeyEvent.Callback interface.

onKeyDown() is called when user presses any key down and keycode represents the particular key is pressed.

So we will overwrite this method in the Activity and keyCode is either KEYCODE_VOLUME_DOWN or KEYCODE_VOLUME_UP.



[sourcecode language=”Java”]
package com.example.volumes;

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

public class MainActivity extends Activity {
static int counter = 0;
TextView tv;

protected void onCreate(Bundle savedInstanceState) {
tv = (TextView) findViewById(R.id.count);
tv.setText("Counter : " + String.valueOf(counter));

public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
tv.setText("Counter : " + String.valueOf(++counter));
Toast.makeText(this, "Volume Down Pressed", Toast.LENGTH_SHORT)
return true;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
tv.setText("Counter : " + String.valueOf(–counter));
Toast.makeText(this, "Volume Up Pressed", Toast.LENGTH_SHORT)
return true;

else {
return super.onKeyDown(keyCode, event);



Overwrite the Volume buttons functionality

Overwrite the Volume buttons functionality

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons