Android examples for Media:Media Volume
Sets media volume and displays volume level.
//package com.java2s; import android.content.Context; import android.media.AudioManager; public class Main { /**// ww w .j a va 2s. c o m * Sets media volume and displays volume level.<br> * When setting the value of parameter 'volume' greater than the maximum value of the media volume will not either cause error or throw exception but maximize the media volume.<br> * Setting the value of volume lower than 0 will minimize the media volume. * * @param context Context * @param volume volume to be changed */ public static void setVolumeWithLevel(Context context, int volume) { adjustMediaVolume(context, volume, AudioManager.FLAG_SHOW_UI); } private static void adjustMediaVolume(Context context, int volume, int flag) { final int MAX_VOLUME = getMaximumVolume(context); final int MIN_VOLUME = 0; if (volume < MIN_VOLUME) { volume = MIN_VOLUME; } else if (volume > MAX_VOLUME) { volume = MAX_VOLUME; } AudioManager audioManager = (AudioManager) context .getSystemService(Context.AUDIO_SERVICE); if (audioManager != null) { audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, flag); } } /** Returns maximum volume the media volume can have * * @param context Context * @return Maximum volume */ public static int getMaximumVolume(Context context) { return ((AudioManager) context .getSystemService(Context.AUDIO_SERVICE)) .getStreamMaxVolume(AudioManager.STREAM_MUSIC); } }