Increases media volume and displays volume level - Android Media

Android examples for Media:Media Volume

Description

Increases media volume and displays volume level

Demo Code


//package com.java2s;
import android.content.Context;
import android.media.AudioManager;

public class Main {
    /**/* www .  ja v a2s .c  om*/
     * Increases media volume and displays volume level
     * 
     * @param context
     */
    public static void increaseVolumeWithLevel(Context context) {
        adjustMediaVolume(context, getCurrentVolume(context) + 1,
                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 current media volume
     * @param context
     * @return current volume
     */
    public static int getCurrentVolume(Context context) {
        AudioManager mAudioManager = (AudioManager) context
                .getSystemService(Context.AUDIO_SERVICE);
        return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    /** 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);
    }
}

Related Tutorials