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

Objec­tive: In this tuto­r­ial you will learn about “How to over­write the default func­tion­al­ity of Vol­ume keys which is to increase or decrease the vol­ume of phone .

We will cre­ate a sim­ple func­tion­al­ity, say a Counter, When you press vol­ume 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 inter­face.

onKey­Down() is called when user presses any key down and key­code rep­re­sents the par­tic­u­lar key is pressed.

So we will over­write this method in the Activ­ity and key­Code is either KEYCODE_VOLUME_DOWN or KEYCODE_VOLUME_UP.

Exam­ple:

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

Over­write the Vol­ume but­tons functionality

You may also like...

Leave a Reply

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