Intercept and synchronize when changing Audio volume in Android?

1

I need to detect when there is a volume change in the Audio channel to synchronize the volume set to SeekBar

By showing for example the dialog where you can adjust the volume

I would like to detect the change made, in order to reflect the change in real time in view.

In my layout I have a SeekBar

sbVolumeBooster = (SeekBar) findViewById(R.id.seek_bar_volume);

To get the maximum volume range and assign the top to SeekBar

sbVolumeBooster.setMax(audioManager.getStreamMaxVolume(streamType));

I intercept the change that can be made to SeekBar to set the volume.

sbVolumeBooster.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
        audioManager.setStreamVolume(streamType, progress, 0);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
});

What I'm missing

When you press the physical buttons to increase or decrease volume, the default Android dialog appears, it shows a bar to change the volume, because I am interested in obtaining the volume that has been left, to synchronize the value to the SeekBar of the view of my app.

    
asked by Webserveis 15.05.2017 в 21:06
source

1 answer

0

Fixed

You can intercept the volume change with ContentObserver to the system configuration properties.

To register the observer

mSettingsContentObserver = new SettingsContentObserver(new Handler());

getApplicationContext().getContentResolver().registerContentObserver(
        android.provider.Settings.System.CONTENT_URI, true,
        mSettingsContentObserver);

To remove the observer

getApplicationContext().getContentResolver().unregisterContentObserver(mSettingsContentObserver);

The configuration change observer

public class SettingsContentObserver extends ContentObserver {

    public SettingsContentObserver(Handler handler) {
        super(handler);
    }

    @Override
    public boolean deliverSelfNotifications() {
        return super.deliverSelfNotifications();
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Log.v(TAG, "Settings change detected " + selfChange);
        int currentVolume = audioManager.getStreamVolume(streamType);
        Log.d(TAG, "Volume now " + currentVolume);
        sbVolumeBooster.setProgress(currentVolume);
    }
}
    
answered by 16.05.2017 в 19:33