Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android BroadCastReceiver for volume key up and down

If a user presses volume key up or down is it possible to detect it in my broadcast receiver? I need the full code.

Here is my Intent filter

IntentFilter filter = new IntentFilter();
filter.addAction("android.media.VOLUME_CHANGED_ACTION");

and my onReceive method is

public void onReceive(Context arg0, Intent intent) {
      KeyEvent ke = (KeyEvent)intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
        if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                System.out.println("I got volume up event");
         }else if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                System.out.println("I got volume key down event");
         }
    }

It gives me a null KeyEvent... any idea?

like image 955
malik M Avatar asked Sep 24 '12 08:09

malik M


1 Answers

The intent does not have an EXTRA_KEY_EVENT extra. It does have an extra android.media.EXTRA_VOLUME_STREAM_VALUE which contains the new volume.

int volume = (Integer)intent.getExtras().get("android.media.EXTRA_VOLUME_STREAM_VALUE");

If you store the old value, you can infer whether volume up or down was pressed.

like image 151
Theus Avatar answered Oct 12 '22 11:10

Theus