Skip to content

Instantly share code, notes, and snippets.

@fiskurgit
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fiskurgit/c6a8db880439e874b745 to your computer and use it in GitHub Desktop.
Save fiskurgit/c6a8db880439e874b745 to your computer and use it in GitHub Desktop.
How to change the global music volume on Android
package com.fiskur.wearvolume;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private TextView mVolumeLabel;
private Button mVolumeUpButton;
private Button mVolumeDownButton;
private AudioManager mAudioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVolumeLabel = (TextView) findViewById(R.id.volume_label);
mVolumeUpButton = (Button) findViewById(R.id.volume_up_button);
mVolumeUpButton.setOnClickListener(this);
mVolumeDownButton = (Button) findViewById(R.id.volume_down_button);
mVolumeDownButton.setOnClickListener(this);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
@Override
public void onClick(View view) {
int maxVolumeIndex = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int volumeIndex = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if(mVolumeUpButton == view){
if(volumeIndex < maxVolumeIndex)volumeIndex++;
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumeIndex, 0);
}else if(mVolumeDownButton == view){
if(volumeIndex > 0)volumeIndex--;
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumeIndex, 0);
}
mVolumeLabel.setText("Max Volume Index: " + maxVolumeIndex + " Volume Index: " + volumeIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment