11

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?

O. K.
  • 3
  • 4
malik M
  • 313
  • 1
  • 7
  • 16

1 Answers1

13

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.

Theus
  • 944
  • 8
  • 9
  • thanks for your answer but its giving me the same volume value = 1 when phone is on silent or vibrate or on ringer volume is at first step. How I can detect phone is silent or vibrate or no first value? – malik M Sep 24 '12 at 09:45
  • 1
    you can use the AudioManager to detect whether you are in vibrate, silent or normal mode: http://stackoverflow.com/questions/2048427/how-can-i-detect-whether-the-android-phone-in-silent-mode-programatically – Theus Sep 24 '12 at 11:06
  • On volume change at max i started the app but when music player running on device then in that case i do not want to open my app on top of volume change.Any help – Sunil Kumar Dec 05 '13 at 07:04