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 telephony call is established.
    970      */
    971     public static final int MODE_IN_CALL            = AudioSystem.MODE_IN_CALL;
    972     /**
    973      * @hide
    974      * In communication audio mode. An audio/video chat or VoIP call is established.
    975      */
    976     public static final int MODE_IN_COMMUNICATION   = AudioSystem.MODE_IN_COMMUNICATION;
    977 
    978     /* Routing bits for setRouting/getRouting API */
    979     /**
    980      * Routing audio output to earpiece
    981      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
    982      * setBluetoothScoOn() methods instead.
    983      */
    984     @Deprecated public static final int ROUTE_EARPIECE          = AudioSystem.ROUTE_EARPIECE;
    985     /**
    986      * Routing audio output to speaker
    987      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
    988      * setBluetoothScoOn() methods instead.
    989      */
    990     @Deprecated public static final int ROUTE_SPEAKER           = AudioSystem.ROUTE_SPEAKER;
    991     /**
    992      * @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
    993      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
    994      * setBluetoothScoOn() methods instead.
    995      */
    996     @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
    997     /**
    998      * Routing audio output to bluetooth SCO
    999      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1000      * setBluetoothScoOn() methods instead.
   1001      */
   1002     @Deprecated public static final int ROUTE_BLUETOOTH_SCO     = AudioSystem.ROUTE_BLUETOOTH_SCO;
   1003     /**
   1004      * Routing audio output to headset
   1005      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1006      * setBluetoothScoOn() methods instead.
   1007      */
   1008     @Deprecated public static final int ROUTE_HEADSET           = AudioSystem.ROUTE_HEADSET;
   1009     /**
   1010      * Routing audio output to bluetooth A2DP
   1011      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1012      * setBluetoothScoOn() methods instead.
   1013      */
   1014     @Deprecated public static final int ROUTE_BLUETOOTH_A2DP    = AudioSystem.ROUTE_BLUETOOTH_A2DP;
   1015     /**
   1016      * Used for mask parameter of {@link #setRouting(int,int,int)}.
   1017      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1018      * setBluetoothScoOn() methods instead.
   1019      */
   1020     @Deprecated public static final int ROUTE_ALL               = AudioSystem.ROUTE_ALL;
   1021 
   1022     /**
   1023      * Sets the audio routing for a specified mode
   1024      *
   1025      * @param mode   audio mode to change route. E.g., MODE_RINGTONE.
   1026      * @param routes bit vector of routes requested, created from one or
   1027      *               more of ROUTE_xxx types. Set bits indicate that route should be on
   1028      * @param mask   bit vector of routes to change, created from one or more of
   1029      * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
   1030      *
   1031      * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
   1032      * setBluetoothScoOn() methods instead.
   1033      */
   1034     @Deprecated
   1035     public void setRouting(int mode, int routes, int mask) {
   1036     }
   1037 
   1038     /**
   1039      * Returns the current audio routing bit vector for a specified mode.
   1040      *
   1041      * @param mode audio mode to get route (e.g., MODE_RINGTONE)
   1042      * @return an audio route bit vector that can be compared with ROUTE_xxx
   1043      * bits
   1044      * @deprecated   Do not query audio routing directly, use isSpeakerphoneOn(),
   1045      * isBluetoothScoOn(), isBluetoothA2dpOn() and isWiredHeadsetOn() methods instead.
   1046      */
   1047     @Deprecated
   1048     public int getRouting(int mode) {
   1049         return -1;
   1050     }
   1051 
   1052     /**
   1053      * Checks whether any music is active.
   1054      *
   1055      * @return true if any music tracks are active.
   1056      */
   1057     public boolean isMusicActive() {
   1058         return AudioSystem.isStreamActive(STREAM_MUSIC);
   1059     }
   1060 
   1061     /*
   1062      * Sets a generic audio configuration parameter. The use of these parameters
   1063      * are platform dependant, see libaudio
   1064      *
   1065      * ** Temporary interface - DO NOT USE
   1066      *
   1067      * TODO: Replace with a more generic key:value get/set mechanism
   1068      *
   1069      * param key   name of parameter to set. Must not be null.
   1070      * param value value of parameter. Must not be null.
   1071      */
   1072     /**
   1073      * @hide
   1074      * @deprecated Use {@link #setPrameters(String)} instead
   1075      */
   1076     @Deprecated public void setParameter(String key, String value) {
   1077         setParameters(key+"="+value);
   1078     }
   1079 
   1080     /**
   1081      * Sets a variable number of parameter values to audio hardware.
   1082      *
   1083      * @param keyValuePairs list of parameters key value pairs in the form:
   1084      *    key1=value1;key2=value2;...
   1085      *
   1086      */
   1087     public void setParameters(String keyValuePairs) {
   1088         AudioSystem.setParameters(keyValuePairs);
   1089     }
   1090 
   1091     /**
   1092      * Sets a varaible number of parameter values to audio hardware.
   1093      *
   1094      * @param keys list of parameters
   1095      * @return list of parameters key value pairs in the form:
   1096      *    key1=value1;key2=value2;...
   1097      */
   1098     public String getParameters(String keys) {
   1099         return AudioSystem.getParameters(keys);
   1100     }
   1101 
   1102     /* Sound effect identifiers */
   1103     /**
   1104      * Keyboard and direction pad click sound
   1105      * @see #playSoundEffect(int)
   1106      */
   1107     public static final int FX_KEY_CLICK = 0;
   1108     /**
   1109      * Focus has moved up
   1110      * @see #playSoundEffect(int)
   1111      */
   1112     public static final int FX_FOCUS_NAVIGATION_UP = 1;
   1113     /**
   1114      * Focus has moved down
   1115      * @see #playSoundEffect(int)
   1116      */
   1117     public static final int FX_FOCUS_NAVIGATION_DOWN = 2;
   1118     /**
   1119      * Focus has moved left
   1120      * @see #playSoundEffect(int)
   1121      */
   1122     public static final int FX_FOCUS_NAVIGATION_LEFT = 3;
   1123     /**
   1124      * Focus has moved right
   1125      * @see #playSoundEffect(int)
   1126      */
   1127     public static final int FX_FOCUS_NAVIGATION_RIGHT = 4;
   1128     /**
   1129      * IME standard keypress sound
   1130      * @see #playSoundEffect(int)
   1131      */
   1132     public static final int FX_KEYPRESS_STANDARD = 5;
   1133     /**
   1134      * IME spacebar keypress sound
   1135      * @see #playSoundEffect(int)
   1136      */
   1137     public static final int FX_KEYPRESS_SPACEBAR = 6;
   1138     /**
   1139      * IME delete keypress sound
   1140      * @see #playSoundEffect(int)
   1141      */
   1142     public static final int FX_KEYPRESS_DELETE = 7;
   1143     /**
   1144      * IME return_keypress sound
   1145      * @see #playSoundEffect(int)
   1146      */
   1147     public static final int FX_KEYPRESS_RETURN = 8;
   1148     /**
   1149      * @hide Number of sound effects
   1150      */
   1151     public static final int NUM_SOUND_EFFECTS = 9;
   1152 
   1153     /**
   1154      * Plays a sound effect (Key clicks, lid open/close...)
   1155      * @param effectType The type of sound effect. One of
   1156      *            {@link #FX_KEY_CLICK},
   1157      *            {@link #FX_FOCUS_NAVIGATION_UP},
   1158      *            {@link #FX_FOCUS_NAVIGATION_DOWN},
   1159      *            {@link #FX_FOCUS_NAVIGATION_LEFT},
   1160      *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
   1161      *            {@link #FX_KEYPRESS_STANDARD},
   1162      *            {@link #FX_KEYPRESS_SPACEBAR},
   1163      *            {@link #FX_KEYPRESS_DELETE},
   1164      *            {@link #FX_KEYPRESS_RETURN},
   1165      * NOTE: This version uses the UI settings to determine
   1166      * whether sounds are heard or not.
   1167      */
   1168     public void  playSoundEffect(int effectType) {
   1169         if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
   1170             return;
   1171         }
   1172 
   1173         if (!querySoundEffectsEnabled()) {
   1174             return;
   1175         }
   1176 
   1177         IAudioService service = getService();
   1178         try {
   1179             service.playSoundEffect(effectType);
   1180         } catch (RemoteException e) {
   1181             Log.e(TAG, "Dead object in playSoundEffect"+e);
   1182         }
   1183     }
   1184 
   1185     /**
   1186      * Plays a sound effect (Key clicks, lid open/close...)
   1187      * @param effectType The type of sound effect. One of
   1188      *            {@link #FX_KEY_CLICK},
   1189      *            {@link #FX_FOCUS_NAVIGATION_UP},
   1190      *            {@link #FX_FOCUS_NAVIGATION_DOWN},
   1191      *            {@link #FX_FOCUS_NAVIGATION_LEFT},
   1192      *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
   1193      *            {@link #FX_KEYPRESS_STANDARD},
   1194      *            {@link #FX_KEYPRESS_SPACEBAR},
   1195      *            {@link #FX_KEYPRESS_DELETE},
   1196      *            {@link #FX_KEYPRESS_RETURN},
   1197      * @param volume Sound effect volume.
   1198      * The volume value is a raw scalar so UI controls should be scaled logarithmically.
   1199      * If a volume of -1 is specified, the AudioManager.STREAM_MUSIC stream volume minus 3dB will be used.
   1200      * NOTE: This version is for applications that have their own
   1201      * settings panel for enabling and controlling volume.
   1202      */
   1203     public void  playSoundEffect(int effectType, float volume) {
   1204         if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
   1205             return;
   1206         }
   1207 
   1208         IAudioService service = getService();
   1209         try {
   1210             service.playSoundEffectVolume(effectType, volume);
   1211         } catch (RemoteException e) {
   1212             Log.e(TAG, "Dead object in playSoundEffect"+e);
   1213         }
   1214     }
   1215 
   1216     /**
   1217      * Settings has an in memory cache, so this is fast.
   1218      */
   1219     private boolean querySoundEffectsEnabled() {
   1220         return Settings.System.getInt(mContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0) != 0;
   1221     }
   1222 
   1223 
   1224     /**
   1225      *  Load Sound effects.
   1226      *  This method must be called when sound effects are enabled.
   1227      */
   1228     public void loadSoundEffects() {
   1229         IAudioService service = getService();
   1230         try {
   1231             service.loadSoundEffects();
   1232         } catch (RemoteException e) {
   1233             Log.e(TAG, "Dead object in loadSoundEffects"+e);
   1234         }
   1235     }
   1236 
   1237     /**
   1238      *  Unload Sound effects.
   1239      *  This method can be called to free some memory when
   1240      *  sound effects are disabled.
   1241      */
   1242     public void unloadSoundEffects() {
   1243         IAudioService service = getService();
   1244         try {
   1245             service.unloadSoundEffects();
   1246         } catch (RemoteException e) {
   1247             Log.e(TAG, "Dead object in unloadSoundEffects"+e);
   1248         }
   1249     }
   1250 
   1251     /**
   1252      * Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
   1253      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1254      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
   1255      */
   1256     public static final int AUDIOFOCUS_GAIN = 1;
   1257     /**
   1258      * Used to indicate a temporary gain or request of audio focus, anticipated to last a short
   1259      * amount of time. Examples of temporary changes are the playback of driving directions, or an
   1260      * event notification.
   1261      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1262      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
   1263      */
   1264     public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
   1265     /**
   1266      * Used to indicate a temporary request of audio focus, anticipated to last a short
   1267      * amount of time, and where it is acceptable for other audio applications to keep playing
   1268      * after having lowered their output level (also referred to as "ducking").
   1269      * Examples of temporary changes are the playback of driving directions where playback of music
   1270      * in the background is acceptable.
   1271      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1272      * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
   1273      */
   1274     public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;
   1275     /**
   1276      * Used to indicate a loss of audio focus of unknown duration.
   1277      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1278      */
   1279     public static final int AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN;
   1280     /**
   1281      * Used to indicate a transient loss of audio focus.
   1282      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1283      */
   1284     public static final int AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT;
   1285     /**
   1286      * Used to indicate a transient loss of audio focus where the loser of the audio focus can
   1287      * lower its output volume if it wants to continue playing (also referred to as "ducking"), as
   1288      * the new focus owner doesn't require others to be silent.
   1289      * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
   1290      */
   1291     public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
   1292             -1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
   1293 
   1294     /**
   1295      * Interface definition for a callback to be invoked when the audio focus of the system is
   1296      * updated.
   1297      */
   1298     public interface OnAudioFocusChangeListener {
   1299         /**
   1300          * Called on the listener to notify it the audio focus for this listener has been changed.
   1301          * The focusChange value indicates whether the focus was gained,
   1302          * whether the focus was lost, and whether that loss is transient, or whether the new focus
   1303          * holder will hold it for an unknown amount of time.
   1304          * When losing focus, listeners can use the focus change information to decide what
   1305          * behavior to adopt when losing focus. A music player could for instance elect to lower
   1306          * the volume of its music stream (duck) for transient focus losses, and pause otherwise.
   1307          * @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
   1308          *   {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
   1309          *   and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
   1310          */
   1311         public void onAudioFocusChange(int focusChange);
   1312     }
   1313 
   1314     /**
   1315      * Map to convert focus event listener IDs, as used in the AudioService audio focus stack,
   1316      * to actual listener objects.
   1317      */
   1318     private HashMap<String, OnAudioFocusChangeListener> mAudioFocusIdListenerMap =
   1319             new HashMap<String, OnAudioFocusChangeListener>();
   1320     /**
   1321      * Lock to prevent concurrent changes to the list of focus listeners for this AudioManager
   1322      * instance.
   1323      */
   1324     private final Object mFocusListenerLock = new Object();
   1325 
   1326     private OnAudioFocusChangeListener findFocusListener(String id) {
   1327         return mAudioFocusIdListenerMap.get(id);
   1328     }
   1329 
   1330     /**
   1331      * Handler for audio focus events coming from the audio service.
   1332      */
   1333     private FocusEventHandlerDelegate mAudioFocusEventHandlerDelegate =
   1334             new FocusEventHandlerDelegate();
   1335 
   1336     /**
   1337      * Helper class to handle the forwarding of audio focus events to the appropriate listener
   1338      */
   1339     private class FocusEventHandlerDelegate {
   1340         private final Handler mHandler;
   1341 
   1342         FocusEventHandlerDelegate() {
   1343             Looper looper;
   1344             if ((looper = Looper.myLooper()) == null) {
   1345                 looper = Looper.getMainLooper();
   1346             }
   1347 
   1348             if (looper != null) {
   1349                 // implement the event handler delegate to receive audio focus events
   1350                 mHandler = new Handler(looper) {
   1351                     @Override
   1352                     public void handleMessage(Message msg) {
   1353                         OnAudioFocusChangeListener listener = null;
   1354                         synchronized(mFocusListenerLock) {
   1355                             listener = findFocusListener((String)msg.obj);
   1356                         }
   1357                         if (listener != null) {
   1358                             listener.onAudioFocusChange(msg.what);
   1359                         }
   1360                     }
   1361                 };
   1362             } else {
   1363                 mHandler = null;
   1364             }
   1365         }
   1366 
   1367         Handler getHandler() {
   1368             return mHandler;
   1369         }
   1370     }
   1371 
   1372     private IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
   1373 
   1374         public void dispatchAudioFocusChange(int focusChange, String id) {
   1375             Message m = mAudioFocusEventHandlerDelegate.getHandler().obtainMessage(focusChange, id);
   1376             mAudioFocusEventHandlerDelegate.getHandler().sendMessage(m);
   1377         }
   1378 
   1379     };
   1380 
   1381     private String getIdForAudioFocusListener(OnAudioFocusChangeListener l) {
   1382         if (l == null) {
   1383             return new String(this.toString());
   1384         } else {
   1385             return new String(this.toString() + l.toString());
   1386         }
   1387     }
   1388 
   1389     /**
   1390      * @hide
   1391      * Registers a listener to be called when audio focus changes. Calling this method is optional
   1392      * before calling {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, as it
   1393      * will register the listener as well if it wasn't registered already.
   1394      * @param l the listener to be notified of audio focus changes.
   1395      */
   1396     public void registerAudioFocusListener(OnAudioFocusChangeListener l) {
   1397         synchronized(mFocusListenerLock) {
   1398             if (mAudioFocusIdListenerMap.containsKey(getIdForAudioFocusListener(l))) {
   1399                 return;
   1400             }
   1401             mAudioFocusIdListenerMap.put(getIdForAudioFocusListener(l), l);
   1402         }
   1403     }
   1404 
   1405     /**
   1406      * @hide
   1407      * Causes the specified listener to not be called anymore when focus is gained or lost.
   1408      * @param l the listener to unregister.
   1409      */
   1410     public void unregisterAudioFocusListener(OnAudioFocusChangeListener l) {
   1411 
   1412         // remove locally
   1413         synchronized(mFocusListenerLock) {
   1414             mAudioFocusIdListenerMap.remove(getIdForAudioFocusListener(l));
   1415         }
   1416     }
   1417 
   1418 
   1419     /**
   1420      * A failed focus change request.
   1421      */
   1422     public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
   1423     /**
   1424      * A successful focus change request.
   1425      */
   1426     public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
   1427 
   1428 
   1429     /**
   1430      *  Request audio focus.
   1431      *  Send a request to obtain the audio focus
   1432      *  @param l the listener to be notified of audio focus changes
   1433      *  @param streamType the main audio stream type affected by the focus request
   1434      *  @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
   1435      *      is temporary, and focus will be abandonned shortly. Examples of transient requests are
   1436      *      for the playback of driving directions, or notifications sounds.
   1437      *      Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
   1438      *      the previous focus owner to keep playing if it ducks its audio output.
   1439      *      Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
   1440      *      as the playback of a song or a video.
   1441      *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
   1442      */
   1443     public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) {
   1444         int status = AUDIOFOCUS_REQUEST_FAILED;
   1445         if ((durationHint < AUDIOFOCUS_GAIN) || (durationHint > AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK))
   1446         {
   1447             Log.e(TAG, "Invalid duration hint, audio focus request denied");
   1448             return status;
   1449         }
   1450         registerAudioFocusListener(l);
   1451         //TODO protect request by permission check?
   1452         IAudioService service = getService();
   1453         try {
   1454             status = service.requestAudioFocus(streamType, durationHint, mICallBack,
   1455                     mAudioFocusDispatcher, getIdForAudioFocusListener(l));
   1456         } catch (RemoteException e) {
   1457             Log.e(TAG, "Can't call requestAudioFocus() from AudioService due to "+e);
   1458         }
   1459         return status;
   1460     }
   1461 
   1462 
   1463     /**
   1464      *  Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
   1465      *  @param l the listener with which focus was requested.
   1466      *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
   1467      */
   1468     public int abandonAudioFocus(OnAudioFocusChangeListener l) {
   1469         int status = AUDIOFOCUS_REQUEST_FAILED;
   1470         unregisterAudioFocusListener(l);
   1471         IAudioService service = getService();
   1472         try {
   1473             status = service.abandonAudioFocus(mAudioFocusDispatcher,
   1474                     getIdForAudioFocusListener(l));
   1475         } catch (RemoteException e) {
   1476             Log.e(TAG, "Can't call abandonAudioFocus() from AudioService due to "+e);
   1477         }
   1478         return status;
   1479     }
   1480 
   1481 
   1482     //====================================================================
   1483     // Remote Control
   1484     /**
   1485      * Register a component to be the sole receiver of MEDIA_BUTTON intents.
   1486      * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
   1487      *      that will receive the media button intent. This broadcast receiver must be declared
   1488      *      in the application manifest.
   1489      */
   1490     public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
   1491         //TODO enforce the rule about the receiver being declared in the manifest
   1492         IAudioService service = getService();
   1493         try {
   1494             service.registerMediaButtonEventReceiver(eventReceiver);
   1495         } catch (RemoteException e) {
   1496             Log.e(TAG, "Dead object in registerMediaButtonEventReceiver"+e);
   1497         }
   1498     }
   1499 
   1500     /**
   1501      * Unregister the receiver of MEDIA_BUTTON intents.
   1502      * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
   1503      *      that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.
   1504      */
   1505     public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
   1506         IAudioService service = getService();
   1507         try {
   1508             service.unregisterMediaButtonEventReceiver(eventReceiver);
   1509         } catch (RemoteException e) {
   1510             Log.e(TAG, "Dead object in unregisterMediaButtonEventReceiver"+e);
   1511         }
   1512     }
   1513 
   1514     /**
   1515      *  @hide
   1516      *  Reload audio settings. This method is called by Settings backup
   1517      *  agent when audio settings are restored and causes the AudioService
   1518      *  to read and apply restored settings.
   1519      */
   1520     public void reloadAudioSettings() {
   1521         IAudioService service = getService();
   1522         try {
   1523             service.reloadAudioSettings();
   1524         } catch (RemoteException e) {
   1525             Log.e(TAG, "Dead object in reloadAudioSettings"+e);
   1526         }
   1527     }
   1528 
   1529      /**
   1530       * {@hide}
   1531       */
   1532      private IBinder mICallBack = new Binder();
   1533 }
   1534