Listen to volume changes events on Android

前端 未结 4 709
梦谈多话
梦谈多话 2020-12-31 09:17

Is there any way to listen to the event of volume change on Android, without just taking over the volume buttons?

The only thing I\'ve found that works is here, but

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 09:32

    You can use : registerMediaButtonEventReceiver (ComponentName eventReceiver) which registers a component to be the sole receiver of MEDIA_BUTTON intents.

    //  in your activity.
    MediaButtonReceiver receiver = new MediaButtonReceiver();
    
    // in onCreate put
    registerMediaButtonEventReceiver(receiver); 
    
    class MediaButtonReceiver implements BroadcastReceiver {
         void onReceive(Intent intent) {
              KeyEvent ke = (KeyEvent)intent.getExtra(Intent.EXTRA_KEY_EVENT); 
              if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                //action when volume goes down
              }
               if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                  //action when volume goes up
              }
         } 
    }
    
       //In both onStop and onPause put :
       unregisterMediaButtonEventReceiver(receiver);
    

    what we are doing here is defining a BroadcastReceiver that deals with ACTION_MEDIA_BUTTON. and use EXTRA_KEY_EVENT which is containing the key event that caused the broadcast to get what was pressed and act upon that.

提交回复
热议问题