Search code examples
androidvolumeseekbar

Android: How to control volume: if volume button up, SeekBar up


I have the following code for my SeekBar:

setVolumeControlStream(AudioManager.STREAM_MUSIC);

            final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup) findViewById(R.id.dialog_root_element));


            SeekBar volControl = (SeekBar)alert.findViewById(R.id.dialog_seekbar);

            volControl.setMax(maxVolume);
            volControl.setProgress(curVolume);
            volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onStopTrackingTouch(SeekBar arg0) {
                }

                @Override
                public void onStartTrackingTouch(SeekBar arg0) {
                }

                @Override
                public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
                }
            });

The problem is that I would like when user decide use volume device buttons, my SeekBar up or down too.

Actually, with this code I can control volume with both methods (device buttons and code) correctly,but when I use volume device buttons, my SeekBar is static.

Any ideas or suggestions?

Thank you!


Solution

  • you can solve this problem by reading the following discussions.

    Is there a listener to listen for changes in the volume in android?

    Taking over the volume key on Android

    Hope this helps.