Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Contact us
Hide Buttons

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.

Example:

MainActivity.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;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		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)
					.show();
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			tv.setText("Counter : " + String.valueOf(--counter));
			Toast.makeText(this, "Volume Up Pressed", Toast.LENGTH_SHORT)
					.show();
			return true;
		}

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

 

Overwrite the Volume buttons functionality

Overwrite the Volume buttons functionality

You may also like...

Leave a Reply

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