Listen to volume changes events on Android

前端 未结 4 652
梦谈多话
梦谈多话 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

    Better, you can register a ContentObserver as follows:

      getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, new ContentObserver(){...} );
    

    Your ContentObserver might look like this:

    public class SettingsContentObserver extends ContentObserver {
        private AudioManager audioManager;
    
        public SettingsContentObserver(Context context, Handler handler) {
            super(handler);
            audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        }
    
        @Override
        public boolean deliverSelfNotifications() {
            return false;
        }
    
        @Override
        public void onChange(boolean selfChange) {
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    
            Log.d(TAG, "Volume now " + currentVolume);
        }
    }
    

    When done:

    getApplicationContext().getContentResolver().unregisterContentObserver(mContentObserver);
    

    One caution, though - sometimes the notifications seem to be delayed if there are lots of button presses quickly.

提交回复
热议问题