Intercept volume button press?

Discussion in 'Android Questions' started by Cothek, Apr 9, 2013.

  1. Cothek

    Cothek Member Licensed User

    I currently have an alarm that plays at a given time and would like to be able to cancel the alarm by pressing either of the volume keys. This would allow the user to silence the alarm if they are in a meeting for example.

    I have tried this method to no avail. What I did was create a new service and add the manifest lines from the link as well as the starting intent but pressing the volume buttons never started the service.

    Any suggestions?
  2. melamoud

    melamoud Active Member Licensed User

    Try this , it worked for me
    in yoiur manifest add the following: (my process name was QVMService,change it to yours)
    AddReceiverText(QVMService, <intent-filter>
        <action android:name=
    "android.intent.action.MEDIA_BUTTON" />
    AddReceiverText(QVMService, <
        <action android:name=
    "" />
    example of code I was using to find the previous/new volume and type you do not need it, just check if the action was volume change, it will work even if the volume was 0 and you pressed volume down, it will have an event of volume level 0 change to volume level 0, so you are safe

    I never saw the event from the media buttons, just the volume change one.


    Dim prevVol As Int
    Dim curVol As Int
    Dim volType As Int

    If (StartingIntent.HasExtra(""AND StartingIntent.HasExtra(""AND StartingIntent.Action = ""Then
          prevVol = StartingIntent.GetExtra(
          curVol = StartingIntent.GetExtra(
          volType = StartingIntent.GetExtra(
  3. stevel05

    stevel05 Expert Licensed User

    If you don't want to run anything via intent, but just know when the keys are pressed so the app can stop the alarm you just need to create the Activity_KeyPress sub like this:

    Sub Activity_KeyPress (KeyCode As Int) As Boolean 'Return True to consume the event
    If KeyCode = KeyCodes.KEYCODE_VOLUME_UP Then 
    Return True
    End If
    If KeyCode = KeyCodes.KEYCODE_VOLUME_DOWN Then 
    Return True
    End If
    End Sub
    Remember to return true so that the volume is not changed at the same time.
    lemonisdead, Peter Simpson and ilan like this.
  4. KY Leng

    KY Leng Member Licensed User

    Hi melamoud,

    the code work properly when the phone screen is not OFF. If I turn off the screen, I could not make my service detect the volume key press.
    Any solution to restart my app with volume key press?

    Best regards,
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice