Search...

Thursday, March 15, 2012

How to changing the ringer volume in Android?


Step1:

Create one layout with seekbar view(main.xml)

Step2:



import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class VolumeActivity extends Activity
{

//a variable to store the seek bar from the XML file
private SeekBar volumeBar;

//an AudioManager object, to change the volume settings
private AudioManager amanager;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //get the seek bar from main.xml file
        volumeBar = (SeekBar) findViewById(R.id.sb_volumebar);

        //get the audio manager
        amanager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

        //seek bar settings//
        //sets the range between 0 and the max volume
        volumeBar.setMax(amanager.getStreamMaxVolume(AudioManager.STREAM_RING));
        //set the seek bar progress to 1
        volumeBar.setKeyProgressIncrement(1);

        //sets the progress of the seek bar based on the system's volume
        volumeBar.setProgress(amanager.getStreamVolume(AudioManager.STREAM_RING));

        //register OnSeekBarChangeListener, so that the seek bar can change the volume
volumeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}

@Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
//change the volume, displaying a toast message containing the current volume and playing a feedback sound
amanager.setStreamVolume(AudioManager.STREAM_RING, progress, AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);
}
});
    }

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//if one of the volume keys were pressed
if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
//change the seek bar progress indicator position
volumeBar.setProgress(amanager.getStreamVolume(AudioManager.STREAM_RING));
}
//propagate the key event
return super.onKeyDown(keyCode, event);
}
}

1 comment:

  1. how it possible set music and system volume on one seekbar ???

    ReplyDelete