Home | History | Annotate | Download | only in media
      1 /*
      2  * Copyright (C) 2007 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.media;
     18 
     19 import android.annotation.SdkConstant;
     20 import android.annotation.SdkConstant.SdkConstantType;
     21 import android.content.ComponentName;
     22 import android.content.Context;
     23 import android.database.ContentObserver;
     24 import android.os.Binder;
     25 import android.os.Handler;
     26 import android.os.IBinder;
     27 import android.os.Looper;
     28 import android.os.Message;
     29 import android.os.RemoteException;
     30 import android.os.ServiceManager;
     31 import android.provider.Settings;
     32 import android.util.Log;
     33 import android.view.KeyEvent;
     34 
     35 import java.util.Iterator;
     36 import java.util.HashMap;
     37 
     38 /**
     39  * AudioManager provides access to volume and ringer mode control.
     40  * <p>
     41  * Use <code>Context.getSystemService(Context.AUDIO_SERVICE)</code> to get
     42  * an instance of this class.
     43  */
     44 public class AudioManager {
     45 
     46     private final Context mContext;
     47     private final Handler mHandler;
     48 
     49     private static String TAG = "AudioManager";
     50     private static boolean DEBUG = false;
     51     private static boolean localLOGV = DEBUG || android.util.Config.LOGV;
     52 
     53     /**
     54      * Broadcast intent, a hint for applications that audio is about to become
     55      * 'noisy' due to a change in audio outputs. For example, this intent may
     56      * be sent when a wired headset is unplugged, or when an A2DP audio
     57      * sink is disconnected, and the audio system is about to automatically
     58      * switch audio route to the speaker. Applications that are controlling
     59      * audio streams may consider pausing, reducing volume or some other action
     60      * on receipt of this intent so as not to surprise the user with audio
     61      * from the speaker.
     62      */
     63     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     64     public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY";
     65 
     66     /**
     67      * Sticky broadcast intent action indicating that the ringer mode has
     68      * changed. Includes the new ringer mode.
     69      *
     70      * @see #EXTRA_RINGER_MODE
     71      */
     72     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     73     public static final String RINGER_MODE_CHANGED_ACTION = "android.media.RINGER_MODE_CHANGED";
     74 
     75     /**
     76      * The new ringer mode.
     77      *
     78      * @see #RINGER_MODE_CHANGED_ACTION
     79      * @see #RINGER_MODE_NORMAL
     80      * @see #RINGER_MODE_SILENT
     81      * @see #RINGER_MODE_VIBRATE
     82      */
     83     public static final String EXTRA_RINGER_MODE = "android.media.EXTRA_RINGER_MODE";
     84 
     85     /**
     86      * Broadcast intent action indicating that the vibrate setting has
     87      * changed. Includes the vibrate type and its new setting.
     88      *
     89      * @see #EXTRA_VIBRATE_TYPE
     90      * @see #EXTRA_VIBRATE_SETTING
     91      */
     92     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     93     public static final String VIBRATE_SETTING_CHANGED_ACTION = "android.media.VIBRATE_SETTING_CHANGED";
     94 
     95     /**
     96      * @hide Broadcast intent when the volume for a particular stream type changes.
     97      * Includes the stream, the new volume and previous volumes
     98      *
     99      * @see #EXTRA_VOLUME_STREAM_TYPE
    100      * @see #EXTRA_VOLUME_STREAM_VALUE
    101      * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
    102      */
    103     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    104     public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";
    105 
    106     /**
    107      * The new vibrate setting for a particular type.
    108      *
    109      * @see #VIBRATE_SETTING_CHANGED_ACTION
    110      * @see #EXTRA_VIBRATE_TYPE
    111      * @see #VIBRATE_SETTING_ON
    112      * @see #VIBRATE_SETTING_OFF
    113      * @see #VIBRATE_SETTING_ONLY_SILENT
    114      */
    115     public static final String EXTRA_VIBRATE_SETTING = "android.media.EXTRA_VIBRATE_SETTING";
    116 
    117     /**
    118      * The vibrate type whose setting has changed.
    119      *
    120      * @see #VIBRATE_SETTING_CHANGED_ACTION
    121      * @see #VIBRATE_TYPE_NOTIFICATION
    122      * @see #VIBRATE_TYPE_RINGER
    123      */
    124     public static final String EXTRA_VIBRATE_TYPE = "android.media.EXTRA_VIBRATE_TYPE";
    125 
    126     /**
    127      * @hide The stream type for the volume changed intent.
    128      */
    129     public static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE";
    130 
    131     /**
    132      * @hide The volume associated with the stream for the volume changed intent.
    133      */
    134     public static final String EXTRA_VOLUME_STREAM_VALUE =
    135         "android.media.EXTRA_VOLUME_STREAM_VALUE";
    136 
    137     /**
    138      * @hide The previous volume associated with the stream for the volume changed intent.
    139      */
    140     public static final String EXTRA_PREV_VOLUME_STREAM_VALUE =
    141         "android.media.EXTRA_PREV_VOLUME_STREAM_VALUE";
    142 
    143     /** The audio stream for phone calls */
    144     public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
    145     /** The audio stream for system sounds */
    146     public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
    147     /** The audio stream for the phone ring */
    148     public static final int STREAM_RING = AudioSystem.STREAM_RING;
    149     /** The audio stream for music playback */
    150     public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
    151     /** The audio stream for alarms */
    152     public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
    153     /** The audio stream for notifications */
    154     public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
    155     /** @hide The audio stream for phone calls when connected to bluetooth */
    156     public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
    157     /** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
    158     public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
    159     /** The audio stream for DTMF Tones */
    160     public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
    161     /** @hide The audio stream for text to speech (TTS) */
    162     public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
    163     /** Number of audio streams */
    164     /**
    165      * @deprecated Use AudioSystem.getNumStreamTypes() instead
    166      */
    167     @Deprecated public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
    168 
    169 
    170     /**  @hide Default volume index values for audio streams */
    171     public static final int[] DEFAULT_STREAM_VOLUME = new int[] {
    172         4,  // STREAM_VOICE_CALL
    173         7,  // STREAM_SYSTEM
    174         5,  // STREAM_RING
    175         11, // STREAM_MUSIC
    176         6,  // STREAM_ALARM
    177         5,  // STREAM_NOTIFICATION
    178         7,  // STREAM_BLUETOOTH_SCO
    179         7,  // STREAM_SYSTEM_ENFORCED
    180         11, // STREAM_DTMF
    181         11  // STREAM_TTS
    182     };
    183 
    184     /**
    185      * Increase the ringer volume.
    186      *
    187      * @see #adjustVolume(int, int)
    188      * @see #adjustStreamVolume(int, int, int)
    189      */
    190     public static final int ADJUST_RAISE = 1;
    191 
    192     /**
    193      * Decrease the ringer volume.
    194      *
    195      * @see #adjustVolume(int, int)
    196      * @see #adjustStreamVolume(int, int, int)
    197      */
    198     public static final int ADJUST_LOWER = -1;
    199 
    200     /**
    201      * Maintain the previous ringer volume. This may be useful when needing to
    202      * show the volume toast without actually modifying the volume.
    203      *
    204      * @see #adjustVolume(int, int)
    205      * @see #adjustStreamVolume(int, int, int)
    206      */
    207     public static final int ADJUST_SAME = 0;
    208 
    209     // Flags should be powers of 2!
    210 
    211     /**
    212      * Show a toast containing the current volume.
    213      *
    214      * @see #adjustStreamVolume(int, int, int)
    215      * @see #adjustVolume(int, int)
    216      * @see #setStreamVolume(int, int, int)
    217      * @see #setRingerMode(int)
    218      */
    219     public static final int FLAG_SHOW_UI = 1 << 0;
    220 
    221     /**
    222      * Whether to include ringer modes as possible options when changing volume.
    223      * For example, if true and volume level is 0 and the volume is adjusted
    224      * with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent or
    225      * vibrate mode.
    226      * <p>
    227      * By default this is on for the ring stream. If this flag is included,
    228      * this behavior will be present regardless of the stream type being
    229      * affected by the ringer mode.
    230      *
    231      * @see #adjustVolume(int, int)
    232      * @see #adjustStreamVolume(int, int, int)
    233      */
    234     public static final int FLAG_ALLOW_RINGER_MODES = 1 << 1;
    235 
    236     /**
    237      * Whether to play a sound when changing the volume.
    238      * <p>
    239      * If this is given to {@link #adjustVolume(int, int)} or
    240      * {@link #adjustSuggestedStreamVolume(int, int, int)}, it may be ignored
    241      * in some cases (for example, the decided stream type is not
    242      * {@link AudioManager#STREAM_RING}, or the volume is being adjusted
    243      * downward).
    244      *
    245      * @see #adjustStreamVolume(int, int, int)
    246      * @see #adjustVolume(int, int)
    247      * @see #setStreamVolume(int, int, int)
    248      */
    249     public static final int FLAG_PLAY_SOUND = 1 << 2;
    250 
    251     /**
    252      * Removes any sounds/vibrate that may be in the queue, or are playing (related to
    253      * changing volume).
    254      */
    255     public static final int FLAG_REMOVE_SOUND_AND_VIBRATE = 1 << 3;
    256 
    257     /**
    258      * Whether to vibrate if going into the vibrate ringer mode.
    259      */
    260     public static final int FLAG_VIBRATE = 1 << 4;
    261 
    262     /**
    263      * Ringer mode that will be silent and will not vibrate. (This overrides the
    264      * vibrate setting.)
    265      *
    266      * @see #setRingerMode(int)
    267      * @see #getRingerMode()
    268      */
    269     public static final int RINGER_MODE_SILENT = 0;
    270 
    271     /**
    272      * Ringer mode that will be silent and will vibrate. (This will cause the
    273      * phone ringer to always vibrate, but the notification vibrate to only
    274      * vibrate if set.)
    275      *
    276      * @see #setRingerMode(int)
    277      * @see #getRingerMode()
    278      */
    279     public static final int RINGER_MODE_VIBRATE = 1;
    280 
    281     /**
    282      * Ringer mode that may be audible and may vibrate. It will be audible if
    283      * the volume before changing out of this mode was audible. It will vibrate
    284      * if the vibrate setting is on.
    285      *
    286      * @see #setRingerMode(int)
    287      * @see #getRingerMode()
    288      */
    289     public static final int RINGER_MODE_NORMAL = 2;
    290 
    291     /**
    292      * Vibrate type that corresponds to the ringer.
    293      *
    294      * @see #setVibrateSetting(int, int)
    295      * @see #getVibrateSetting(int)
    296      * @see #shouldVibrate(int)
    297      */
    298     public static final int VIBRATE_TYPE_RINGER = 0;
    299 
    300     /**
    301      * Vibrate type that corresponds to notifications.
    302      *
    303      * @see #setVibrateSetting(int, int)
    304      * @see #getVibrateSetting(int)
    305      * @see #shouldVibrate(int)
    306      */
    307     public static final int VIBRATE_TYPE_NOTIFICATION = 1;
    308 
    309     /**
    310      * Vibrate setting that suggests to never vibrate.
    311      *
    312      * @see #setVibrateSetting(int, int)
    313      * @see #getVibrateSetting(int)
    314      */
    315     public static final int VIBRATE_SETTING_OFF = 0;
    316 
    317     /**
    318      * Vibrate setting that suggests to vibrate when possible.
    319      *
    320      * @see #setVibrateSetting(int, int)
    321      * @see #getVibrateSetting(int)
    322      */
    323     public static final int VIBRATE_SETTING_ON = 1;
    324 
    325     /**
    326      * Vibrate setting that suggests to only vibrate when in the vibrate ringer
    327      * mode.
    328      *
    329      * @see #setVibrateSetting(int, int)
    330      * @see #getVibrateSetting(int)
    331      */
    332     public static final int VIBRATE_SETTING_ONLY_SILENT = 2;
    333 
    334     /**
    335      * Suggests using the default stream type. This may not be used in all
    336      * places a stream type is needed.
    337      */
    338     public static final int USE_DEFAULT_STREAM_TYPE = Integer.MIN_VALUE;
    339 
    340     private static IAudioService sService;
    341 
    342     /**
    343      * @hide
    344      */
    345     public AudioManager(Context context) {
    346         mContext = context;
    347         mHandler = new Handler(context.getMainLooper());
    348     }
    349 
    350     private static IAudioService getService()
    351     {
    352         if (sService != null) {
    353             return sService;
    354         }
    355         IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
    356         sService = IAudioService.Stub.asInterface(b);
    357         return sService;
    358     }
    359 
    360     /**
    361      * Adjusts the volume of a particular stream by one step in a direction.
    362      * <p>
    363      * This method should only be used by applications that replace the platform-wide
    364      * management of audio settings or the main telephony application.
    365      *
    366      * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL},
    367      * {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC} or
    368      * {@link #STREAM_ALARM}
    369      * @param direction The direction to adjust the volume. One of
    370      *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
    371      *            {@link #ADJUST_SAME}.
    372      * @param flags One or more flags.
    373      * @see #adjustVolume(int, int)
    374      * @see #setStreamVolume(int, int, int)
    375      */
    376     public void adjustStreamVolume(int streamType, int direction, int flags) {
    377         IAudioService service = getService();
    378         try {
    379             service.adjustStreamVolume(streamType, direction, flags);
    380         } catch (RemoteException e) {
    381             Log.e(TAG, "Dead object in adjustStreamVolume", e);
    382         }
    383     }
    384 
    385     /**
    386      * Adjusts the volume of the most relevant stream. For example, if a call is
    387      * active, it will have the highest priority regardless of if the in-call
    388      * screen is showing. Another example, if music is playing in the background
    389      * and a call is not active, the music stream will be adjusted.
    390      * <p>
    391      * This method should only be used by applications that replace the platform-wide
    392      * management of audio settings or the main telephony application.
    393      *
    394      * @param direction The direction to adjust the volume. One of
    395      *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
    396      *            {@link #ADJUST_SAME}.
    397      * @param flags One or more flags.
    398      * @see #adjustSuggestedStreamVolume(int, int, int)
    399      * @see #adjustStreamVolume(int, int, int)
    400      * @see #setStreamVolume(int, int, int)
    401      */
    402     public void adjustVolume(int direction, int flags) {
    403         IAudioService service = getService();
    404         try {
    405             service.adjustVolume(direction, flags);
    406         } catch (RemoteException e) {
    407             Log.e(TAG, "Dead object in adjustVolume", e);
    408         }
    409     }
    410 
    411     /**
    412      * Adjusts the volume of the most relevant stream, or the given fallback
    413      * stream.
    414      * <p>
    415      * This method should only be used by applications that replace the platform-wide
    416      * management of audio settings or the main telephony application.
    417      *
    418      * @param direction The direction to adjust the volume. One of
    419      *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
    420      *            {@link #ADJUST_SAME}.
    421      * @param suggestedStreamType The stream type that will be used if there
    422      *            isn't a relevant stream. {@link #USE_DEFAULT_STREAM_TYPE} is valid here.
    423      * @param flags One or more flags.
    424      * @see #adjustVolume(int, int)
    425      * @see #adjustStreamVolume(int, int, int)
    426      * @see #setStreamVolume(int, int, int)
    427      */
    428     public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
    429         IAudioService service = getService();
    430         try {
    431             service.adjustSuggestedStreamVolume(direction, suggestedStreamType, flags);
    432         } catch (RemoteException e) {
    433             Log.e(TAG, "Dead object in adjustVolume", e);
    434         }
    435     }
    436 
    437     /**
    438      * Returns the current ringtone mode.
    439      *
    440      * @return The current ringtone mode, one of {@link #RINGER_MODE_NORMAL},
    441      *         {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
    442      * @see #setRingerMode(int)
    443      */
    444     public int getRingerMode() {
    445         IAudioService service = getService();
    446         try {
    447             return service.getRingerMode();
    448         } catch (RemoteException e) {
    449             Log.e(TAG, "Dead object in getRingerMode", e);
    450             return RINGER_MODE_NORMAL;
    451         }
    452     }
    453 
    454     /**
    455      * Returns the maximum volume index for a particular stream.
    456      *
    457      * @param streamType The stream type whose maximum volume index is returned.
    458      * @return The maximum valid volume index for the stream.
    459      * @see #getStreamVolume(int)
    460      */
    461     public int getStreamMaxVolume(int streamType) {
    462         IAudioService service = getService();
    463         try {
    464             return service.getStreamMaxVolume(streamType);
    465         } catch (RemoteException e) {
    466             Log.e(TAG, "Dead object in getStreamMaxVolume", e);
    467             return 0;
    468         }
    469     }
    470 
    471     /**
    472      * Returns the current volume index for a particular stream.
    473      *
    474      * @param streamType The stream type whose volume index is returned.
    475      * @return The current volume index for the stream.
    476      * @see #getStreamMaxVolume(int)
    477      * @see #setStreamVolume(int, int, int)
    478      */
    479     public int getStreamVolume(int streamType) {
    480         IAudioService service = getService();
    481         try {
    482             return service.getStreamVolume(streamType);
    483         } catch (RemoteException e) {
    484             Log.e(TAG, "Dead object in getStreamVolume", e);
    485             return 0;
    486         }
    487     }
    488 
    489     /**
    490      * Sets the ringer mode.
    491      * <p>
    492      * Silent mode will mute the volume and will not vibrate. Vibrate mode will
    493      * mute the volume and vibrate. Normal mode will be audible and may vibrate
    494      * according to user settings.
    495      *
    496      * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},
    497      *            {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
    498      * @see #getRingerMode()
    499      */
    500     public void setRingerMode(int ringerMode) {
    501         IAudioService service = getService();
    502         try {
    503             service.setRingerMode(ringerMode);
    504         } catch (RemoteException e) {
    505             Log.e(TAG, "Dead object in setRingerMode", e);
    506         }
    507     }
    508 
    509     /**
    510      * Sets the volume index for a particular stream.
    511      *
    512      * @param streamType The stream whose volume index should be set.
    513      * @param index The volume index to set. See
    514      *            {@link #getStreamMaxVolume(int)} for the largest valid value.
    515      * @param flags One or more flags.
    516      * @see #getStreamMaxVolume(int)
    517      * @see #getStreamVolume(int)
    518      */
    519     public void setStreamVolume(int streamType, int index, int flags) {
    520         IAudioService service = getService();
    521         try {
    522             service.setStreamVolume(streamType, index, flags);
    523         } catch (RemoteException e) {
    524             Log.e(TAG, "Dead object in setStreamVolume", e);
    525         }
    526     }
    527 
    528     /**
    529      * Solo or unsolo a particular stream. All other streams are muted.
    530      * <p>
    531      * The solo command is protected against client process death: if a process
    532      * with an active solo request on a stream dies, all streams that were muted
    533      * because of this request will be unmuted automatically.
    534      * <p>
    535      * The solo requests for a given stream are cumulative: the AudioManager
    536      * can receive several solo requests from one or more clients and the stream
    537      * will be unsoloed only when the same number of unsolo requests are received.
    538      * <p>
    539      * For a better user experience, applications MUST unsolo a soloed stream
    540      * in onPause() and solo is again in onResume() if appropriate.
    541      *
    542      * @param streamType The stream to be soloed/unsoloed.
    543      * @param state The required solo state: true for solo ON, false for solo OFF
    544      */
    545     public void setStreamSolo(int streamType, boolean state) {
    546         IAudioService service = getService();
    547         try {
    548             service.setStreamSolo(streamType, state, mICallBack);
    549         } catch (RemoteException e) {
    550             Log.e(TAG, "Dead object in setStreamSolo", e);
    551         }
    552     }
    553 
    554     /**
    555      * Mute or unmute an audio stream.
    556      * <p>
    557      * The mute command is protected against client process death: if a process
    558      * with an active mute request on a stream dies, this stream will be unmuted
    559      * automatically.
    560      * <p>
    561      * The mute requests for a given stream are cumulative: the AudioManager
    562      * can receive several mute requests from one or more clients and the stream
    563      * will be unmuted only when the same number of unmute requests are received.
    564      * <p>
    565      * For a better user experience, applications MUST unmute a muted stream
    566      * in onPause() and mute is again in onResume() if appropriate.
    567      * <p>
    568      * This method should only be used by applications that replace the platform-wide
    569      * management of audio settings or the main telephony application.
    570      *
    571      * @param streamType The stream to be muted/unmuted.
    572      * @param state The required mute state: true for mute ON, false for mute OFF
    573      */
    574     public void setStreamMute(int streamType, boolean state) {
    575         IAudioService service = getService();
    576         try {
    577             service.setStreamMute(streamType, state, mICallBack);
    578         } catch (RemoteException e) {
    579             Log.e(TAG, "Dead object in setStreamMute", e);
    580         }
    581     }
    582 
    583     /**
    584      * Returns whether a particular type should vibrate according to user
    585      * settings and the current ringer mode.
    586      * <p>
    587      * This shouldn't be needed by most clients that use notifications to
    588      * vibrate. The notification manager will not vibrate if the policy doesn't
    589      * allow it, so the client should always set a vibrate pattern and let the
    590      * notification manager control whether or not to actually vibrate.
    591      *
    592      * @param vibrateType The type of vibrate. One of
    593      *            {@link #VIBRATE_TYPE_NOTIFICATION} or
    594      *            {@link #VIBRATE_TYPE_RINGER}.
    595      * @return Whether the type should vibrate at the instant this method is
    596      *         called.
    597      * @see #setVibrateSetting(int, int)
    598      * @see #getVibrateSetting(int)
    599      */
    600     public boolean shouldVibrate(int vibrateType) {
    601         IAudioService service = getService();
    602         try {
    603             return service.shouldVibrate(vibrateType);
    604         } catch (RemoteException e) {
    605             Log.e(TAG, "Dead object in shouldVibrate", e);
    606             return false;
    607         }
    608     }
    609 
    610     /**
    611      * Returns whether the user's vibrate setting for a vibrate type.
    612      * <p>
    613      * This shouldn't be needed by most clients that want to vibrate, instead
    614      * see {@link #shouldVibrate(int)}.
    615      *
    616      * @param vibrateType The type of vibrate. One of
    617      *            {@link #VIBRATE_TYPE_NOTIFICATION} or
    618      *            {@link #VIBRATE_TYPE_RINGER}.
    619      * @return The vibrate setting, one of {@link #VIBRATE_SETTING_ON},
    620      *         {@link #VIBRATE_SETTING_OFF}, or
    621      *         {@link #VIBRATE_SETTING_ONLY_SILENT}.
    622      * @see #setVibrateSetting(int, int)
    623      * @see #shouldVibrate(int)
    624      */
    625     public int getVibrateSetting(int vibrateType) {
    626         IAudioService service = getService();
    627         try {
    628             return service.getVibrateSetting(vibrateType);
    629         } catch (RemoteException e) {
    630             Log.e(TAG, "Dead object in getVibrateSetting", e);
    631             return VIBRATE_SETTING_OFF;
    632         }
    633     }
    634 
    635     /**
    636      * Sets the setting for when the vibrate type should vibrate.
    637      * <p>
    638      * This method should only be used by applications that replace the platform-wide
    639      * management of audio settings or the main telephony application.
    640      *
    641      * @param vibrateType The type of vibrate. One of
    642      *            {@link #VIBRATE_TYPE_NOTIFICATION} or
    643      *            {@link #VIBRATE_TYPE_RINGER}.
    644      * @param vibrateSetting The vibrate setting, one of
    645      *            {@link #VIBRATE_SETTING_ON},
    646      *            {@link #VIBRATE_SETTING_OFF}, or
    647      *            {@link #VIBRATE_SETTING_ONLY_SILENT}.
    648      * @see #getVibrateSetting(int)
    649      * @see #shouldVibrate(int)
    650      */
    651     public void setVibrateSetting(int vibrateType, int vibrateSetting) {
    652         IAudioService service = getService();
    653         try {
    654             service.setVibrateSetting(vibrateType, vibrateSetting);
    655         } catch (RemoteException e) {
    656             Log.e(TAG, "Dead object in setVibrateSetting", e);
    657         }
    658     }
    659 
    660     /**
    661      * Sets the speakerphone on or off.
    662      * <p>
    663      * This method should only be used by applications that replace the platform-wide
    664      * management of audio settings or the main telephony application.
    665      *
    666      * @param on set <var>true</var> to turn on speakerphone;
    667      *           <var>false</var> to turn it off
    668      */
    669     public void setSpeakerphoneOn(boolean on){
    670         IAudioService service = getService();
    671         try {
    672             service.setSpeakerphoneOn(on);
    673         } catch (RemoteException e) {
    674             Log.e(TAG, "Dead object in setSpeakerphoneOn", e);
    675         }
    676     }
    677 
    678     /**
    679      * Checks whether the speakerphone is on or off.
    680      *
    681      * @return true if speakerphone is on, false if it's off
    682      */
    683     public boolean isSpeakerphoneOn() {
    684         IAudioService service = getService();
    685         try {
    686             return service.isSpeakerphoneOn();
    687         } catch (RemoteException e) {
    688             Log.e(TAG, "Dead object in isSpeakerphoneOn", e);
    689             return false;
    690         }
    691      }
    692 
    693     //====================================================================
    694     // Bluetooth SCO control
    695     /**
    696      * Sticky broadcast intent action indicating that the bluetoooth SCO audio
    697      * connection state has changed. The intent contains on extra {@link #EXTRA_SCO_AUDIO_STATE}
    698      * indicating the new state which is either {@link #SCO_AUDIO_STATE_DISCONNECTED}
    699      * or {@link #SCO_AUDIO_STATE_CONNECTED}
    700      *
    701      * @see #startBluetoothSco()
    702      */
    703     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
    704     public static final String ACTION_SCO_AUDIO_STATE_CHANGED =
    705             "android.media.SCO_AUDIO_STATE_CHANGED";
    706     /**
    707      * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_CHANGED} containing the new
    708      * bluetooth SCO connection state.
    709      */
    710     public static final String EXTRA_SCO_AUDIO_STATE =
    711             "android.media.extra.SCO_AUDIO_STATE";
    712 
    713     /**
    714      * Value for extra {@link #EXTRA_SCO_AUDIO_STATE} indicating that the
    715      * SCO audio channel is not established
    716      */
    717     public static final int SCO_AUDIO_STATE_DISCONNECTED = 0;
    718     /**
    719      * Value for extra {@link #EXTRA_SCO_AUDIO_STATE} indicating that the
    720      * SCO audio channel is established
    721      */
    722     public static final int SCO_AUDIO_STATE_CONNECTED = 1;
    723     /**
    724      * Value for extra {@link #EXTRA_SCO_AUDIO_STATE} indicating that
    725      * there was an error trying to obtain the state
    726      */
    727     public static final int SCO_AUDIO_STATE_ERROR = -1;
    728 
    729 
    730     /**
    731      * Indicates if current platform supports use of SCO for off call use cases.
    732      * Application wanted to use bluetooth SCO audio when the phone is not in call
    733      * must first call thsi method to make sure that the platform supports this
    734      * feature.
    735      * @return true if bluetooth SCO can be used for audio when not in call
    736      *         false otherwise
    737      * @see #startBluetoothSco()
    738     */
    739     public boolean isBluetoothScoAvailableOffCall() {
    740         return mContext.getResources().getBoolean(
    741                com.android.internal.R.bool.config_bluetooth_sco_off_call);
    742     }
    743 
    744     /**
    745      * Start bluetooth SCO audio connection.
    746      * <p>Requires Permission:
    747      *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
    748      * <p>This method can be used by applications wanting to send and received audio
    749      * to/from a bluetooth SCO headset while the phone is not in call.
    750      * <p>As the SCO connection establishment can take several seconds,
    751      * applications should not rely on the connection to be available when the method
    752      * returns but instead register to receive the intent {@link #ACTION_SCO_AUDIO_STATE_CHANGED}
    753      * and wait for the state to be {@link #SCO_AUDIO_STATE_CONNECTED}.
    754      * <p>As the connection is not guaranteed to succeed, applications must wait for this intent with
    755      * a timeout.
    756      * <p>When finished with the SCO connection or if the establishment times out,
    757      * the application must call {@link #stopBluetoothSco()} to clear the request and turn
    758      * down the bluetooth connection.
    759      * <p>Even if a SCO connection is established, the following restrictions apply on audio
    760      * output streams so that they can be routed to SCO headset:
    761      * - the stream type must be {@link #STREAM_VOICE_CALL}
    762      * - the format must be mono
    763      * - the sampling must be 16kHz or 8kHz
    764      * <p>The following restrictions apply on input streams:
    765      * - the format must be mono
    766      * - the sampling must be 8kHz
    767      *
    768      * <p>Note that the phone application always has the priority on the usage of the SCO
    769      * connection for telephony. If this method is called while the phone is in call
    770      * it will be ignored. Similarly, if a call is received or sent while an application
    771      * is using the SCO connection, the connection will be lost for the application and NOT
    772      * returned automatically when the call ends.
    773      * @see #stopBluetoothSco()
    774      * @see #ACTION_SCO_AUDIO_STATE_CHANGED
    775      */
    776     public void startBluetoothSco(){
    777         IAudioService service = getService();
    778         try {
    779             service.startBluetoothSco(mICallBack);
    780         } catch (RemoteException e) {
    781             Log.e(TAG, "Dead object in startBluetoothSco", e);
    782         }
    783     }
    784 
    785     /**
    786      * Stop bluetooth SCO audio connection.
    787      * <p>Requires Permission:
    788      *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
    789      * <p>This method must be called by applications having requested the use of
    790      * bluetooth SCO audio with {@link #startBluetoothSco()}
    791      * when finished with the SCO connection or if the establishment times out.
    792      * @see #startBluetoothSco()
    793      */
    794     public void stopBluetoothSco(){
    795         IAudioService service = getService();
    796         try {
    797             service.stopBluetoothSco(mICallBack);
    798         } catch (RemoteException e) {
    799             Log.e(TAG, "Dead object in stopBluetoothSco", e);
    800         }
    801     }
    802 
    803     /**
    804      * Request use of Bluetooth SCO headset for communications.
    805      * <p>
    806      * This method should only be used by applications that replace the platform-wide
    807      * management of audio settings or the main telephony application.
    808      *
    809      * @param on set <var>true</var> to use bluetooth SCO for communications;
    810      *               <var>false</var> to not use bluetooth SCO for communications
    811      */
    812     public void setBluetoothScoOn(boolean on){
    813         IAudioService service = getService();
    814         try {
    815             service.setBluetoothScoOn(on);
    816         } catch (RemoteException e) {
    817             Log.e(TAG, "Dead object in setBluetoothScoOn", e);
    818         }
    819     }
    820 
    821     /**
    822      * Checks whether communications use Bluetooth SCO.
    823      *
    824      * @return true if SCO is used for communications;
    825      *         false if otherwise
    826      */
    827     public boolean isBluetoothScoOn() {
    828         IAudioService service = getService();
    829         try {
    830             return service.isBluetoothScoOn();
    831         } catch (RemoteException e) {
    832             Log.e(TAG, "Dead object in isBluetoothScoOn", e);
    833             return false;
    834         }
    835     }
    836 
    837     /**
    838      * @param on set <var>true</var> to route A2DP audio to/from Bluetooth
    839      *           headset; <var>false</var> disable A2DP audio
    840      * @deprecated Do not use.
    841      */
    842     @Deprecated public void setBluetoothA2dpOn(boolean on){
    843     }
    844 
    845     /**
    846      * Checks whether A2DP audio routing to the Bluetooth headset is on or off.
    847      *
    848      * @return true if A2DP audio is being routed to/from Bluetooth headset;
    849      *         false if otherwise
    850      */
    851     public boolean isBluetoothA2dpOn() {
    852         if (AudioSystem.getDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,"")
    853             == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
    854             return false;
    855         } else {
    856             return true;
    857         }
    858     }
    859 
    860     /**
    861      * Sets audio routing to the wired headset on or off.
    862      *
    863      * @param on set <var>true</var> to route audio to/from wired
    864      *           headset; <var>false</var> disable wired headset audio
    865      * @deprecated Do not use.
    866      */
    867     @Deprecated public void setWiredHeadsetOn(boolean on){
    868     }
    869 
    870     /**
    871      * Checks whether audio routing to the wired headset is on or off.
    872      *
    873      * @return true if audio is being routed to/from wired headset;
    874      *         false if otherwise
    875      */
    876     public boolean isWiredHeadsetOn() {
    877         if (AudioSystem.getDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,"")
    878                 == AudioSystem.DEVICE_STATE_UNAVAILABLE &&
    879             AudioSystem.getDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,"")
    880                 == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
    881             return false;
    882         } else {
    883             return true;
    884         }
    885     }
    886 
    887     /**
    888      * Sets the microphone mute on or off.
    889      * <p>
    890      * This method should only be used by applications that replace the platform-wide
    891      * management of audio settings or the main telephony application.
    892      *
    893      * @param on set <var>true</var> to mute the microphone;
    894      *           <var>false</var> to turn mute off
    895      */
    896     public void setMicrophoneMute(boolean on){
    897         AudioSystem.muteMicrophone(on);
    898     }
    899 
    900     /**
    901      * Checks whether the microphone mute is on or off.
    902      *
    903      * @return true if microphone is muted, false if it's not
    904      */
    905     public boolean isMicrophoneMute() {
    906         return AudioSystem.isMicrophoneMuted();
    907     }
    908 
    909     /**
    910      * Sets the audio mode.
    911      * <p>
    912      * The audio mode encompasses audio routing AND the behavior of
    913      * the telephony layer. Therefore this method should only be used by applications that
    914      * replace the platform-wide management of audio settings or the main telephony application.
    915      * In particular, the {@link #MODE_IN_CALL} mode should only be used by the telephony
    916      * application when it places a phone call, as it will cause signals from the radio layer
    917      * to feed the platform mixer.
    918      *
    919      * @param mode  the requested audio mode (NORMAL, RINGTONE, or IN_CALL).
    920      *              Informs the HAL about the current audio state so that
    921      *              it can route the audio appropriately.
    922      */
    923     public void setMode(int mode) {
    924         IAudioService service = getService();
    925         try {
    926             service.setMode(mode, mICallBack);
    927         } catch (RemoteException e) {
    928             Log.e(TAG, "Dead object in setMode", e);
    929         }
    930     }
    931 
    932     /**
    933      * Returns the current audio mode.
    934      *
    935      * @return      the current audio mode (NORMAL, RINGTONE, or IN_CALL).
    936      *              Returns the current current audio state from the HAL.
    937      */
    938     public int getMode() {
    939         IAudioService service = getService();
    940         try {
    941             return service.getMode();
    942         } catch (RemoteException e) {
    943             Log.e(TAG, "Dead object in getMode", e);
    944             return MODE_INVALID;
    945         }
    946     }
    947 
    948     /* modes for setMode/getMode/setRoute/getRoute */
    949     /**
    950      * Audio harware modes.
    951      */
    952     /**
    953      * Invalid audio mode.
    954      */
    955     public static final int MODE_INVALID            = AudioSystem.MODE_INVALID;
    956     /**
    957      * Current audio mode. Used to apply audio routing to current mode.
    958      */
    959     public static final int MODE_CURRENT            = AudioSystem.MODE_CURRENT;
    960     /**
    961      * Normal audio mode: not ringing and no call established.
    962      */
    963     public static final int MODE_NORMAL             = AudioSystem.MODE_NORMAL;
    964     /**
    965      * Ringing audio mode. An incoming is being signaled.
    966      */
    967     public static final int MODE_RINGTONE           = AudioSystem.MODE_RINGTONE;
    968     /**
    969      * In call audio mode. A call is established.
    970      */
    971     public static final int MODE_IN_CALL            = AudioSystem.MODE_IN_CALL;
    972 
    973     /* Routing bits for setRouting/getRouting API */
    974     /**
    975      * Routing audio output to earpiece
    976      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
    977      * setBluetoothScoOn() methods instead.
    978      */
    979     @Deprecated public static final int ROUTE_EARPIECE          = AudioSystem.ROUTE_EARPIECE;
    980     /**
    981      * Routing audio output to speaker
    982      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
    983      * setBluetoothScoOn() methods instead.
    984      */
    985     @Deprecated public static final int ROUTE_SPEAKER           = AudioSystem.ROUTE_SPEAKER;
    986     /**
    987      * @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
    988      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
    989      * setBluetoothScoOn() methods instead.
    990      */
    991     @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
    992     /**
    993      * Routing audio output to bluetooth SCO
    994      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
    995      * setBluetoothScoOn() methods instead.
    996      */
    997     @Deprecated public static final int ROUTE_BLUETOOTH_SCO     = AudioSystem.ROUTE_BLUETOOTH_SCO;
    998     /**
    999      * Routing audio output to headset
   1000      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1001      * setBluetoothScoOn() methods instead.
   1002      */
   1003     @Deprecated public static final int ROUTE_HEADSET           = AudioSystem.ROUTE_HEADSET;
   1004     /**
   1005      * Routing audio output to bluetooth A2DP
   1006      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1007      * setBluetoothScoOn() methods instead.
   1008      */
   1009     @Deprecated public static final int ROUTE_BLUETOOTH_A2DP    = AudioSystem.ROUTE_BLUETOOTH_A2DP;
   1010     /**
   1011      * Used for mask parameter of {@link #setRouting(int,int,int)}.
   1012      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1013      * setBluetoothScoOn() methods instead.
   1014      */
   1015     @Deprecated public static final int ROUTE_ALL               = AudioSystem.ROUTE_ALL;
   1016 
   1017     /**
   1018      * Sets the audio routing for a specified mode
   1019      *
   1020      * @param mode   audio mode to change route. E.g., MODE_RINGTONE.
   1021      * @param routes bit vector of routes requested, created from one or
   1022      *               more of ROUTE_xxx types. Set bits indicate that route should be on
   1023      * @param mask   bit vector of routes to change, created from one or more of
   1024      * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
   1025      *
   1026      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1027      * setBluetoothScoOn() methods instead.
   1028      */
   1029     @Deprecated
   1030     public void setRouting(int mode, int routes, int mask) {
   1031     }
   1032 
   1033     /**
   1034      * Returns the current audio routing bit vector for a specified mode.
   1035      *
   1036      * @param mode audio mode to get route (e.g., MODE_RINGTONE)
   1037      * @return an audio route bit vector that can be compared with ROUTE_xxx
   1038      * bits
   1039      * @deprecated   Do not query audio routing directly, use isSpeakerphoneOn(),
   1040      * isBluetoothScoOn(), isBluetoothA2dpOn() and isWiredHeadsetOn() methods instead.
   1041      */
   1042     @Deprecated
   1043     public int getRouting(int mode) {
   1044         return -1;
   1045     }
   1046 
   1047     /**
   1048      * Checks whether any music is active.
   1049      *
   1050      * @return true if any music tracks are active.
   1051      */
   1052     public boolean isMusicActive() {
   1053         return AudioSystem.isStreamActive(STREAM_MUSIC);
   1054     }
   1055 
   1056     /*
   1057      * Sets a generic audio configuration parameter. The use of these parameters
   1058      * are platform dependant, see libaudio
   1059      *
   1060      * ** Temporary interface - DO NOT USE
   1061      *
   1062      * TODO: Replace with a more generic key:value get/set mechanism
   1063      *
   1064      * param key   name of parameter to set. Must not be null.
   1065      * param value value of parameter. Must not be null.
   1066      */
   1067     /**
   1068      * @hide
   1069      * @deprecated Use {@link #setPrameters(String)} instead
   1070      */
   1071     @Deprecated public void setParameter(String key, String value) {
   1072         setParameters(key+"="+value);
   1073     }
   1074 
   1075     /**
   1076      * Sets a variable number of parameter values to audio hardware.
   1077      *
   1078      * @param keyValuePairs list of parameters key value pairs in the form:
   1079      *    key1=value1;key2=value2;...
   1080      *
   1081      */
   1082     public void setParameters(String keyValuePairs) {
   1083         AudioSystem.setParameters(keyValuePairs);
   1084     }
   1085 
   1086     /**
   1087      * Sets a varaible number of parameter values to audio hardware.
   1088      *
   1089      * @param keys list of parameters
   1090      * @return list of parameters key value pairs in the form:
   1091      *    key1=value1;key2=value2;...
   1092      */
   1093     public String getParameters(String keys) {
   1094         return AudioSystem.getParameters(keys);
   1095     }
   1096 
   1097     /* Sound effect identifiers */
   1098     /**
   1099      * Keyboard and direction pad click sound
   1100      * @see #playSoundEffect(int)
   1101      */
   1102     public static final int FX_KEY_CLICK = 0;
   1103     /**
   1104      * Focus has moved up
   1105      * @see #playSoundEffect(int)
   1106      */
   1107     public static final int FX_FOCUS_NAVIGATION_UP = 1;
   1108     /**
   1109      * Focus has moved down
   1110      * @see #playSoundEffect(int)
   1111      */
   1112     public static final int FX_FOCUS_NAVIGATION_DOWN = 2;
   1113     /**
   1114      * Focus has moved left
   1115      * @see #playSoundEffect(int)
   1116      */
   1117     public static final int FX_FOCUS_NAVIGATION_LEFT = 3;
   1118     /**
   1119      * Focus has moved right
   1120      * @see #playSoundEffect(int)
   1121      */
   1122     public static final int FX_FOCUS_NAVIGATION_RIGHT = 4;
   1123     /**
   1124      * IME standard keypress sound
   1125      * @see #playSoundEffect(int)
   1126      */
   1127     public static final int FX_KEYPRESS_STANDARD = 5;
   1128     /**
   1129      * IME spacebar keypress sound
   1130      * @see #playSoundEffect(int)
   1131      */
   1132     public static final int FX_KEYPRESS_SPACEBAR = 6;
   1133     /**
   1134      * IME delete keypress sound
   1135      * @see #playSoundEffect(int)
   1136      */
   1137     public static final int FX_KEYPRESS_DELETE = 7;
   1138     /**
   1139      * IME return_keypress sound
   1140      * @see #playSoundEffect(int)
   1141      */
   1142     public static final int FX_KEYPRESS_RETURN = 8;
   1143     /**
   1144      * @hide Number of sound effects
   1145      */
   1146     public static final int NUM_SOUND_EFFECTS = 9;
   1147 
   1148     /**
   1149      * Plays a sound effect (Key clicks, lid open/close...)
   1150      * @param effectType The type of sound effect. One of
   1151      *            {@link #FX_KEY_CLICK},
   1152      *            {@link #FX_FOCUS_NAVIGATION_UP},
   1153      *            {@link #FX_FOCUS_NAVIGATION_DOWN},
   1154      *            {@link #FX_FOCUS_NAVIGATION_LEFT},
   1155      *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
   1156      *            {@link #FX_KEYPRESS_STANDARD},
   1157      *            {@link #FX_KEYPRESS_SPACEBAR},
   1158      *            {@link #FX_KEYPRESS_DELETE},
   1159      *            {@link #FX_KEYPRESS_RETURN},
   1160      * NOTE: This version uses the UI settings to determine
   1161      * whether sounds are heard or not.
   1162      */
   1163     public void  playSoundEffect(int effectType) {
   1164         if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
   1165             return;
   1166         }
   1167 
   1168         if (!querySoundEffectsEnabled()) {
   1169             return;
   1170         }
   1171 
   1172         IAudioService service = getService();
   1173         try {
   1174             service.playSoundEffect(effectType);
   1175         } catch (RemoteException e) {
   1176             Log.e(TAG, "Dead object in playSoundEffect"+e);
   1177         }
   1178     }
   1179 
   1180     /**
   1181      * Plays a sound effect (Key clicks, lid open/close...)
   1182      * @param effectType The type of sound effect. One of
   1183      *            {@link #FX_KEY_CLICK},
   1184      *            {@link #FX_FOCUS_NAVIGATION_UP},
   1185      *            {@link #FX_FOCUS_NAVIGATION_DOWN},
   1186      *            {@link #FX_FOCUS_NAVIGATION_LEFT},
   1187      *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
   1188      *            {@link #FX_KEYPRESS_STANDARD},
   1189      *            {@link #FX_KEYPRESS_SPACEBAR},
   1190      *            {@link #FX_KEYPRESS_DELETE},
   1191      *            {@link #FX_KEYPRESS_RETURN},
   1192      * @param volume Sound effect volume.
   1193      * The volume value is a raw scalar so UI controls should be scaled logarithmically.
   1194      * If a volume of -1 is specified, the AudioManager.STREAM_MUSIC stream volume minus 3dB will be used.
   1195      * NOTE: This version is for applications that have their own
   1196      * settings panel for enabling and controlling volume.
   1197      */
   1198     public void  playSoundEffect(int effectType, float volume) {
   1199         if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
   1200             return;
   1201         }
   1202 
   1203         IAudioService service = getService();
   1204         try {
   1205             service.playSoundEffectVolume(effectType, volume);
   1206         } catch (RemoteException e) {
   1207             Log.e(TAG, "Dead object in playSoundEffect"+e);
   1208         }
   1209     }
   1210 
   1211     /**
   1212      * Settings has an in memory cache, so this is fast.
   1213      */
   1214     private boolean querySoundEffectsEnabled() {
   1215         return Settings.System.getInt(mContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0) != 0;
   1216     }
   1217 
   1218 
   1219     /**
   1220      *  Load Sound effects.
   1221      *  This method must be called when sound effects are enabled.
   1222      */
   1223     public void loadSoundEffects() {
   1224         IAudioService service = getService();
   1225         try {
   1226             service.loadSoundEffects();
   1227         } catch (RemoteException e) {
   1228             Log.e(TAG, "Dead object in loadSoundEffects"+e);
   1229         }
   1230     }
   1231 
   1232     /**
   1233      *  Unload Sound effects.
   1234      *  This method can be called to free some memory when
   1235      *  sound effects are disabled.
   1236      */
   1237     public void unloadSoundEffects() {
   1238         IAudioService service = getService();
   1239         try {
   1240             service.unloadSoundEffects();
   1241         } catch (RemoteException e) {
   1242             Log.e(TAG, "Dead object in unloadSoundEffects"+e);
   1243         }
   1244     }
   1245 
   1246     /**
   1247      * Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
   1248      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1249      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
   1250      */
   1251     public static final int AUDIOFOCUS_GAIN = 1;
   1252     /**
   1253      * Used to indicate a temporary gain or request of audio focus, anticipated to last a short
   1254      * amount of time. Examples of temporary changes are the playback of driving directions, or an
   1255      * event notification.
   1256      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1257      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
   1258      */
   1259     public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
   1260     /**
   1261      * Used to indicate a temporary request of audio focus, anticipated to last a short
   1262      * amount of time, and where it is acceptable for other audio applications to keep playing
   1263      * after having lowered their output level (also referred to as "ducking").
   1264      * Examples of temporary changes are the playback of driving directions where playback of music
   1265      * in the background is acceptable.
   1266      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1267      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
   1268      */
   1269     public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;
   1270     /**
   1271      * Used to indicate a loss of audio focus of unknown duration.
   1272      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1273      */
   1274     public static final int AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN;
   1275     /**
   1276      * Used to indicate a transient loss of audio focus.
   1277      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1278      */
   1279     public static final int AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT;
   1280     /**
   1281      * Used to indicate a transient loss of audio focus where the loser of the audio focus can
   1282      * lower its output volume if it wants to continue playing (also referred to as "ducking"), as
   1283      * the new focus owner doesn't require others to be silent.
   1284      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1285      */
   1286     public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
   1287             -1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
   1288 
   1289     /**
   1290      * Interface definition for a callback to be invoked when the audio focus of the system is
   1291      * updated.
   1292      */
   1293     public interface OnAudioFocusChangeListener {
   1294         /**
   1295          * Called on the listener to notify it the audio focus for this listener has been changed.
   1296          * The focusChange value indicates whether the focus was gained,
   1297          * whether the focus was lost, and whether that loss is transient, or whether the new focus
   1298          * holder will hold it for an unknown amount of time.
   1299          * When losing focus, listeners can use the focus change information to decide what
   1300          * behavior to adopt when losing focus. A music player could for instance elect to lower
   1301          * the volume of its music stream (duck) for transient focus losses, and pause otherwise.
   1302          * @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
   1303          *   {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
   1304          *   and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
   1305          */
   1306         public void onAudioFocusChange(int focusChange);
   1307     }
   1308 
   1309     /**
   1310      * Map to convert focus event listener IDs, as used in the AudioService audio focus stack,
   1311      * to actual listener objects.
   1312      */
   1313     private HashMap<String, OnAudioFocusChangeListener> mAudioFocusIdListenerMap =
   1314             new HashMap<String, OnAudioFocusChangeListener>();
   1315     /**
   1316      * Lock to prevent concurrent changes to the list of focus listeners for this AudioManager
   1317      * instance.
   1318      */
   1319     private final Object mFocusListenerLock = new Object();
   1320 
   1321     private OnAudioFocusChangeListener findFocusListener(String id) {
   1322         return mAudioFocusIdListenerMap.get(id);
   1323     }
   1324 
   1325     /**
   1326      * Handler for audio focus events coming from the audio service.
   1327      */
   1328     private FocusEventHandlerDelegate mAudioFocusEventHandlerDelegate =
   1329             new FocusEventHandlerDelegate();
   1330 
   1331     /**
   1332      * Helper class to handle the forwarding of audio focus events to the appropriate listener
   1333      */
   1334     private class FocusEventHandlerDelegate {
   1335         private final Handler mHandler;
   1336 
   1337         FocusEventHandlerDelegate() {
   1338             Looper looper;
   1339             if ((looper = Looper.myLooper()) == null) {
   1340                 looper = Looper.getMainLooper();
   1341             }
   1342 
   1343             if (looper != null) {
   1344                 // implement the event handler delegate to receive audio focus events
   1345                 mHandler = new Handler(looper) {
   1346                     @Override
   1347                     public void handleMessage(Message msg) {
   1348                         OnAudioFocusChangeListener listener = null;
   1349                         synchronized(mFocusListenerLock) {
   1350                             listener = findFocusListener((String)msg.obj);
   1351                         }
   1352                         if (listener != null) {
   1353                             listener.onAudioFocusChange(msg.what);
   1354                         }
   1355                     }
   1356                 };
   1357             } else {
   1358                 mHandler = null;
   1359             }
   1360         }
   1361 
   1362         Handler getHandler() {
   1363             return mHandler;
   1364         }
   1365     }
   1366 
   1367     private IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
   1368 
   1369         public void dispatchAudioFocusChange(int focusChange, String id) {
   1370             Message m = mAudioFocusEventHandlerDelegate.getHandler().obtainMessage(focusChange, id);
   1371             mAudioFocusEventHandlerDelegate.getHandler().sendMessage(m);
   1372         }
   1373 
   1374     };
   1375 
   1376     private String getIdForAudioFocusListener(OnAudioFocusChangeListener l) {
   1377         if (l == null) {
   1378             return new String(this.toString());
   1379         } else {
   1380             return new String(this.toString() + l.toString());
   1381         }
   1382     }
   1383 
   1384     /**
   1385      * @hide
   1386      * Registers a listener to be called when audio focus changes. Calling this method is optional
   1387      * before calling {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, as it
   1388      * will register the listener as well if it wasn't registered already.
   1389      * @param l the listener to be notified of audio focus changes.
   1390      */
   1391     public void registerAudioFocusListener(OnAudioFocusChangeListener l) {
   1392         synchronized(mFocusListenerLock) {
   1393             if (mAudioFocusIdListenerMap.containsKey(getIdForAudioFocusListener(l))) {
   1394                 return;
   1395             }
   1396             mAudioFocusIdListenerMap.put(getIdForAudioFocusListener(l), l);
   1397         }
   1398     }
   1399 
   1400     /**
   1401      * @hide
   1402      * Causes the specified listener to not be called anymore when focus is gained or lost.
   1403      * @param l the listener to unregister.
   1404      */
   1405     public void unregisterAudioFocusListener(OnAudioFocusChangeListener l) {
   1406 
   1407         // remove locally
   1408         synchronized(mFocusListenerLock) {
   1409             mAudioFocusIdListenerMap.remove(getIdForAudioFocusListener(l));
   1410         }
   1411     }
   1412 
   1413 
   1414     /**
   1415      * A failed focus change request.
   1416      */
   1417     public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
   1418     /**
   1419      * A successful focus change request.
   1420      */
   1421     public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
   1422 
   1423 
   1424     /**
   1425      *  Request audio focus.
   1426      *  Send a request to obtain the audio focus
   1427      *  @param l the listener to be notified of audio focus changes
   1428      *  @param streamType the main audio stream type affected by the focus request
   1429      *  @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
   1430      *      is temporary, and focus will be abandonned shortly. Examples of transient requests are
   1431      *      for the playback of driving directions, or notifications sounds.
   1432      *      Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
   1433      *      the previous focus owner to keep playing if it ducks its audio output.
   1434      *      Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
   1435      *      as the playback of a song or a video.
   1436      *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
   1437      */
   1438     public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) {
   1439         int status = AUDIOFOCUS_REQUEST_FAILED;
   1440         if ((durationHint < AUDIOFOCUS_GAIN) || (durationHint > AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK))
   1441         {
   1442             Log.e(TAG, "Invalid duration hint, audio focus request denied");
   1443             return status;
   1444         }
   1445         registerAudioFocusListener(l);
   1446         //TODO protect request by permission check?
   1447         IAudioService service = getService();
   1448         try {
   1449             status = service.requestAudioFocus(streamType, durationHint, mICallBack,
   1450                     mAudioFocusDispatcher, getIdForAudioFocusListener(l));
   1451         } catch (RemoteException e) {
   1452             Log.e(TAG, "Can't call requestAudioFocus() from AudioService due to "+e);
   1453         }
   1454         return status;
   1455     }
   1456 
   1457 
   1458     /**
   1459      *  Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
   1460      *  @param l the listener with which focus was requested.
   1461      *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
   1462      */
   1463     public int abandonAudioFocus(OnAudioFocusChangeListener l) {
   1464         int status = AUDIOFOCUS_REQUEST_FAILED;
   1465         unregisterAudioFocusListener(l);
   1466         IAudioService service = getService();
   1467         try {
   1468             status = service.abandonAudioFocus(mAudioFocusDispatcher,
   1469                     getIdForAudioFocusListener(l));
   1470         } catch (RemoteException e) {
   1471             Log.e(TAG, "Can't call abandonAudioFocus() from AudioService due to "+e);
   1472         }
   1473         return status;
   1474     }
   1475 
   1476 
   1477     //====================================================================
   1478     // Remote Control
   1479     /**
   1480      * Register a component to be the sole receiver of MEDIA_BUTTON intents.
   1481      * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
   1482      *      that will receive the media button intent. This broadcast receiver must be declared
   1483      *      in the application manifest.
   1484      */
   1485     public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
   1486         //TODO enforce the rule about the receiver being declared in the manifest
   1487         IAudioService service = getService();
   1488         try {
   1489             service.registerMediaButtonEventReceiver(eventReceiver);
   1490         } catch (RemoteException e) {
   1491             Log.e(TAG, "Dead object in registerMediaButtonEventReceiver"+e);
   1492         }
   1493     }
   1494 
   1495     /**
   1496      * Unregister the receiver of MEDIA_BUTTON intents.
   1497      * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
   1498      *      that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.
   1499      */
   1500     public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
   1501         IAudioService service = getService();
   1502         try {
   1503             service.unregisterMediaButtonEventReceiver(eventReceiver);
   1504         } catch (RemoteException e) {
   1505             Log.e(TAG, "Dead object in unregisterMediaButtonEventReceiver"+e);
   1506         }
   1507     }
   1508 
   1509     /**
   1510      *  @hide
   1511      *  Reload audio settings. This method is called by Settings backup
   1512      *  agent when audio settings are restored and causes the AudioService
   1513      *  to read and apply restored settings.
   1514      */
   1515     public void reloadAudioSettings() {
   1516         IAudioService service = getService();
   1517         try {
   1518             service.reloadAudioSettings();
   1519         } catch (RemoteException e) {
   1520             Log.e(TAG, "Dead object in reloadAudioSettings"+e);
   1521         }
   1522     }
   1523 
   1524      /**
   1525       * {@hide}
   1526       */
   1527      private IBinder mICallBack = new Binder();
   1528 }
   1529