AudioManager.java revision c0ed6efe5f9b3c06a1297592647bd52a0f84215a
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
17package android.media;
18
19import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.app.PendingIntent;
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.os.Binder;
26import android.os.Handler;
27import android.os.IBinder;
28import android.os.Looper;
29import android.os.Message;
30import android.os.RemoteException;
31import android.os.SystemClock;
32import android.os.ServiceManager;
33import android.provider.Settings;
34import android.util.Log;
35import android.view.KeyEvent;
36import android.view.VolumePanel;
37
38import java.util.HashMap;
39
40/**
41 * AudioManager provides access to volume and ringer mode control.
42 * <p>
43 * Use <code>Context.getSystemService(Context.AUDIO_SERVICE)</code> to get
44 * an instance of this class.
45 */
46public class AudioManager {
47
48    private final Context mContext;
49    private long mVolumeKeyUpTime;
50    private final boolean mUseMasterVolume;
51    private final boolean mUseVolumeKeySounds;
52    private static String TAG = "AudioManager";
53
54    /**
55     * Broadcast intent, a hint for applications that audio is about to become
56     * 'noisy' due to a change in audio outputs. For example, this intent may
57     * be sent when a wired headset is unplugged, or when an A2DP audio
58     * sink is disconnected, and the audio system is about to automatically
59     * switch audio route to the speaker. Applications that are controlling
60     * audio streams may consider pausing, reducing volume or some other action
61     * on receipt of this intent so as not to surprise the user with audio
62     * from the speaker.
63     */
64    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
65    public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY";
66
67    /**
68     * Sticky broadcast intent action indicating that the ringer mode has
69     * changed. Includes the new ringer mode.
70     *
71     * @see #EXTRA_RINGER_MODE
72     */
73    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
74    public static final String RINGER_MODE_CHANGED_ACTION = "android.media.RINGER_MODE_CHANGED";
75
76    /**
77     * The new ringer mode.
78     *
79     * @see #RINGER_MODE_CHANGED_ACTION
80     * @see #RINGER_MODE_NORMAL
81     * @see #RINGER_MODE_SILENT
82     * @see #RINGER_MODE_VIBRATE
83     */
84    public static final String EXTRA_RINGER_MODE = "android.media.EXTRA_RINGER_MODE";
85
86    /**
87     * Broadcast intent action indicating that the vibrate setting has
88     * changed. Includes the vibrate type and its new setting.
89     *
90     * @see #EXTRA_VIBRATE_TYPE
91     * @see #EXTRA_VIBRATE_SETTING
92     * @deprecated Applications should maintain their own vibrate policy based on
93     * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
94     */
95    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
96    public static final String VIBRATE_SETTING_CHANGED_ACTION =
97        "android.media.VIBRATE_SETTING_CHANGED";
98
99    /**
100     * @hide Broadcast intent when the volume for a particular stream type changes.
101     * Includes the stream, the new volume and previous volumes
102     *
103     * @see #EXTRA_VOLUME_STREAM_TYPE
104     * @see #EXTRA_VOLUME_STREAM_VALUE
105     * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
106     */
107    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
108    public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";
109
110    /**
111     * @hide Broadcast intent when the master volume changes.
112     * Includes the new volume
113     *
114     * @see #EXTRA_MASTER_VOLUME_VALUE
115     * @see #EXTRA_PREV_MASTER_VOLUME_VALUE
116     */
117    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
118    public static final String MASTER_VOLUME_CHANGED_ACTION =
119        "android.media.MASTER_VOLUME_CHANGED_ACTION";
120
121    /**
122     * @hide Broadcast intent when the master mute state changes.
123     * Includes the the new volume
124     *
125     * @see #EXTRA_MASTER_VOLUME_MUTED
126     */
127    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
128    public static final String MASTER_MUTE_CHANGED_ACTION =
129        "android.media.MASTER_MUTE_CHANGED_ACTION";
130
131    /**
132     * The new vibrate setting for a particular type.
133     *
134     * @see #VIBRATE_SETTING_CHANGED_ACTION
135     * @see #EXTRA_VIBRATE_TYPE
136     * @see #VIBRATE_SETTING_ON
137     * @see #VIBRATE_SETTING_OFF
138     * @see #VIBRATE_SETTING_ONLY_SILENT
139     * @deprecated Applications should maintain their own vibrate policy based on
140     * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
141     */
142    public static final String EXTRA_VIBRATE_SETTING = "android.media.EXTRA_VIBRATE_SETTING";
143
144    /**
145     * The vibrate type whose setting has changed.
146     *
147     * @see #VIBRATE_SETTING_CHANGED_ACTION
148     * @see #VIBRATE_TYPE_NOTIFICATION
149     * @see #VIBRATE_TYPE_RINGER
150     * @deprecated Applications should maintain their own vibrate policy based on
151     * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
152     */
153    public static final String EXTRA_VIBRATE_TYPE = "android.media.EXTRA_VIBRATE_TYPE";
154
155    /**
156     * @hide The stream type for the volume changed intent.
157     */
158    public static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE";
159
160    /**
161     * @hide The volume associated with the stream for the volume changed intent.
162     */
163    public static final String EXTRA_VOLUME_STREAM_VALUE =
164        "android.media.EXTRA_VOLUME_STREAM_VALUE";
165
166    /**
167     * @hide The previous volume associated with the stream for the volume changed intent.
168     */
169    public static final String EXTRA_PREV_VOLUME_STREAM_VALUE =
170        "android.media.EXTRA_PREV_VOLUME_STREAM_VALUE";
171
172    /**
173     * @hide The new master volume value for the master volume changed intent.
174     * Value is integer between 0 and 100 inclusive.
175     */
176    public static final String EXTRA_MASTER_VOLUME_VALUE =
177        "android.media.EXTRA_MASTER_VOLUME_VALUE";
178
179    /**
180     * @hide The previous master volume value for the master volume changed intent.
181     * Value is integer between 0 and 100 inclusive.
182     */
183    public static final String EXTRA_PREV_MASTER_VOLUME_VALUE =
184        "android.media.EXTRA_PREV_MASTER_VOLUME_VALUE";
185
186    /**
187     * @hide The new master volume mute state for the master mute changed intent.
188     * Value is boolean
189     */
190    public static final String EXTRA_MASTER_VOLUME_MUTED =
191        "android.media.EXTRA_MASTER_VOLUME_MUTED";
192
193    /** The audio stream for phone calls */
194    public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
195    /** The audio stream for system sounds */
196    public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
197    /** The audio stream for the phone ring */
198    public static final int STREAM_RING = AudioSystem.STREAM_RING;
199    /** The audio stream for music playback */
200    public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
201    /** The audio stream for alarms */
202    public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
203    /** The audio stream for notifications */
204    public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
205    /** @hide The audio stream for phone calls when connected to bluetooth */
206    public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
207    /** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
208    public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
209    /** The audio stream for DTMF Tones */
210    public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
211    /** @hide The audio stream for text to speech (TTS) */
212    public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
213    /** Number of audio streams */
214    /**
215     * @deprecated Use AudioSystem.getNumStreamTypes() instead
216     */
217    @Deprecated public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
218
219
220    /**  @hide Default volume index values for audio streams */
221    public static final int[] DEFAULT_STREAM_VOLUME = new int[] {
222        4,  // STREAM_VOICE_CALL
223        7,  // STREAM_SYSTEM
224        5,  // STREAM_RING
225        11, // STREAM_MUSIC
226        6,  // STREAM_ALARM
227        5,  // STREAM_NOTIFICATION
228        7,  // STREAM_BLUETOOTH_SCO
229        7,  // STREAM_SYSTEM_ENFORCED
230        11, // STREAM_DTMF
231        11  // STREAM_TTS
232    };
233
234    /**
235     * Increase the ringer volume.
236     *
237     * @see #adjustVolume(int, int)
238     * @see #adjustStreamVolume(int, int, int)
239     */
240    public static final int ADJUST_RAISE = 1;
241
242    /**
243     * Decrease the ringer volume.
244     *
245     * @see #adjustVolume(int, int)
246     * @see #adjustStreamVolume(int, int, int)
247     */
248    public static final int ADJUST_LOWER = -1;
249
250    /**
251     * Maintain the previous ringer volume. This may be useful when needing to
252     * show the volume toast without actually modifying the volume.
253     *
254     * @see #adjustVolume(int, int)
255     * @see #adjustStreamVolume(int, int, int)
256     */
257    public static final int ADJUST_SAME = 0;
258
259    // Flags should be powers of 2!
260
261    /**
262     * Show a toast containing the current volume.
263     *
264     * @see #adjustStreamVolume(int, int, int)
265     * @see #adjustVolume(int, int)
266     * @see #setStreamVolume(int, int, int)
267     * @see #setRingerMode(int)
268     */
269    public static final int FLAG_SHOW_UI = 1 << 0;
270
271    /**
272     * Whether to include ringer modes as possible options when changing volume.
273     * For example, if true and volume level is 0 and the volume is adjusted
274     * with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent or
275     * vibrate mode.
276     * <p>
277     * By default this is on for the ring stream. If this flag is included,
278     * this behavior will be present regardless of the stream type being
279     * affected by the ringer mode.
280     *
281     * @see #adjustVolume(int, int)
282     * @see #adjustStreamVolume(int, int, int)
283     */
284    public static final int FLAG_ALLOW_RINGER_MODES = 1 << 1;
285
286    /**
287     * Whether to play a sound when changing the volume.
288     * <p>
289     * If this is given to {@link #adjustVolume(int, int)} or
290     * {@link #adjustSuggestedStreamVolume(int, int, int)}, it may be ignored
291     * in some cases (for example, the decided stream type is not
292     * {@link AudioManager#STREAM_RING}, or the volume is being adjusted
293     * downward).
294     *
295     * @see #adjustStreamVolume(int, int, int)
296     * @see #adjustVolume(int, int)
297     * @see #setStreamVolume(int, int, int)
298     */
299    public static final int FLAG_PLAY_SOUND = 1 << 2;
300
301    /**
302     * Removes any sounds/vibrate that may be in the queue, or are playing (related to
303     * changing volume).
304     */
305    public static final int FLAG_REMOVE_SOUND_AND_VIBRATE = 1 << 3;
306
307    /**
308     * Whether to vibrate if going into the vibrate ringer mode.
309     */
310    public static final int FLAG_VIBRATE = 1 << 4;
311
312    /**
313     * Ringer mode that will be silent and will not vibrate. (This overrides the
314     * vibrate setting.)
315     *
316     * @see #setRingerMode(int)
317     * @see #getRingerMode()
318     */
319    public static final int RINGER_MODE_SILENT = 0;
320
321    /**
322     * Ringer mode that will be silent and will vibrate. (This will cause the
323     * phone ringer to always vibrate, but the notification vibrate to only
324     * vibrate if set.)
325     *
326     * @see #setRingerMode(int)
327     * @see #getRingerMode()
328     */
329    public static final int RINGER_MODE_VIBRATE = 1;
330
331    /**
332     * Ringer mode that may be audible and may vibrate. It will be audible if
333     * the volume before changing out of this mode was audible. It will vibrate
334     * if the vibrate setting is on.
335     *
336     * @see #setRingerMode(int)
337     * @see #getRingerMode()
338     */
339    public static final int RINGER_MODE_NORMAL = 2;
340
341    // maximum valid ringer mode value. Values must start from 0 and be contiguous.
342    private static final int RINGER_MODE_MAX = RINGER_MODE_NORMAL;
343
344    /**
345     * Vibrate type that corresponds to the ringer.
346     *
347     * @see #setVibrateSetting(int, int)
348     * @see #getVibrateSetting(int)
349     * @see #shouldVibrate(int)
350     * @deprecated Applications should maintain their own vibrate policy based on
351     * current ringer mode that can be queried via {@link #getRingerMode()}.
352     */
353    public static final int VIBRATE_TYPE_RINGER = 0;
354
355    /**
356     * Vibrate type that corresponds to notifications.
357     *
358     * @see #setVibrateSetting(int, int)
359     * @see #getVibrateSetting(int)
360     * @see #shouldVibrate(int)
361     * @deprecated Applications should maintain their own vibrate policy based on
362     * current ringer mode that can be queried via {@link #getRingerMode()}.
363     */
364    public static final int VIBRATE_TYPE_NOTIFICATION = 1;
365
366    /**
367     * Vibrate setting that suggests to never vibrate.
368     *
369     * @see #setVibrateSetting(int, int)
370     * @see #getVibrateSetting(int)
371     * @deprecated Applications should maintain their own vibrate policy based on
372     * current ringer mode that can be queried via {@link #getRingerMode()}.
373     */
374    public static final int VIBRATE_SETTING_OFF = 0;
375
376    /**
377     * Vibrate setting that suggests to vibrate when possible.
378     *
379     * @see #setVibrateSetting(int, int)
380     * @see #getVibrateSetting(int)
381     * @deprecated Applications should maintain their own vibrate policy based on
382     * current ringer mode that can be queried via {@link #getRingerMode()}.
383     */
384    public static final int VIBRATE_SETTING_ON = 1;
385
386    /**
387     * Vibrate setting that suggests to only vibrate when in the vibrate ringer
388     * mode.
389     *
390     * @see #setVibrateSetting(int, int)
391     * @see #getVibrateSetting(int)
392     * @deprecated Applications should maintain their own vibrate policy based on
393     * current ringer mode that can be queried via {@link #getRingerMode()}.
394     */
395    public static final int VIBRATE_SETTING_ONLY_SILENT = 2;
396
397    /**
398     * Suggests using the default stream type. This may not be used in all
399     * places a stream type is needed.
400     */
401    public static final int USE_DEFAULT_STREAM_TYPE = Integer.MIN_VALUE;
402
403    private static IAudioService sService;
404
405    /**
406     * @hide
407     */
408    public AudioManager(Context context) {
409        mContext = context;
410        mUseMasterVolume = mContext.getResources().getBoolean(
411                com.android.internal.R.bool.config_useMasterVolume);
412        mUseVolumeKeySounds = mContext.getResources().getBoolean(
413                com.android.internal.R.bool.config_useVolumeKeySounds);
414    }
415
416    private static IAudioService getService()
417    {
418        if (sService != null) {
419            return sService;
420        }
421        IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
422        sService = IAudioService.Stub.asInterface(b);
423        return sService;
424    }
425
426    /**
427     * @hide
428     */
429    public void preDispatchKeyEvent(KeyEvent event, int stream) {
430        /*
431         * If the user hits another key within the play sound delay, then
432         * cancel the sound
433         */
434        int keyCode = event.getKeyCode();
435        if (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_UP
436                && keyCode != KeyEvent.KEYCODE_VOLUME_MUTE
437                && mVolumeKeyUpTime + VolumePanel.PLAY_SOUND_DELAY
438                        > SystemClock.uptimeMillis()) {
439            /*
440             * The user has hit another key during the delay (e.g., 300ms)
441             * since the last volume key up, so cancel any sounds.
442             */
443            if (mUseMasterVolume) {
444                adjustMasterVolume(ADJUST_SAME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
445            } else {
446                adjustSuggestedStreamVolume(ADJUST_SAME,
447                        stream, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
448            }
449        }
450    }
451
452    /**
453     * @hide
454     */
455    public void handleKeyDown(KeyEvent event, int stream) {
456        int keyCode = event.getKeyCode();
457        switch (keyCode) {
458            case KeyEvent.KEYCODE_VOLUME_UP:
459            case KeyEvent.KEYCODE_VOLUME_DOWN:
460                /*
461                 * Adjust the volume in on key down since it is more
462                 * responsive to the user.
463                 */
464                int flags = FLAG_SHOW_UI | FLAG_VIBRATE;
465
466                if (mUseMasterVolume) {
467                    adjustMasterVolume(
468                            keyCode == KeyEvent.KEYCODE_VOLUME_UP
469                                    ? ADJUST_RAISE
470                                    : ADJUST_LOWER,
471                            flags);
472                } else {
473                    adjustSuggestedStreamVolume(
474                            keyCode == KeyEvent.KEYCODE_VOLUME_UP
475                                    ? ADJUST_RAISE
476                                    : ADJUST_LOWER,
477                            stream,
478                            flags);
479                }
480                break;
481            case KeyEvent.KEYCODE_VOLUME_MUTE:
482                if (event.getRepeatCount() == 0) {
483                    if (mUseMasterVolume) {
484                        setMasterMute(!isMasterMute());
485                    } else {
486                        // TODO: Actually handle MUTE.
487                    }
488                }
489                break;
490        }
491    }
492
493    /**
494     * @hide
495     */
496    public void handleKeyUp(KeyEvent event, int stream) {
497        int keyCode = event.getKeyCode();
498        switch (keyCode) {
499            case KeyEvent.KEYCODE_VOLUME_UP:
500            case KeyEvent.KEYCODE_VOLUME_DOWN:
501                /*
502                 * Play a sound. This is done on key up since we don't want the
503                 * sound to play when a user holds down volume down to mute.
504                 */
505                if (mUseVolumeKeySounds) {
506                    if (mUseMasterVolume) {
507                        adjustMasterVolume(ADJUST_SAME, FLAG_PLAY_SOUND);
508                    } else {
509                        int flags = FLAG_PLAY_SOUND;
510                        adjustSuggestedStreamVolume(
511                                ADJUST_SAME,
512                                stream,
513                                flags);
514                    }
515                }
516                mVolumeKeyUpTime = SystemClock.uptimeMillis();
517                break;
518        }
519    }
520
521    /**
522     * Adjusts the volume of a particular stream by one step in a direction.
523     * <p>
524     * This method should only be used by applications that replace the platform-wide
525     * management of audio settings or the main telephony application.
526     *
527     * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL},
528     * {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC} or
529     * {@link #STREAM_ALARM}
530     * @param direction The direction to adjust the volume. One of
531     *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
532     *            {@link #ADJUST_SAME}.
533     * @param flags One or more flags.
534     * @see #adjustVolume(int, int)
535     * @see #setStreamVolume(int, int, int)
536     */
537    public void adjustStreamVolume(int streamType, int direction, int flags) {
538        IAudioService service = getService();
539        try {
540            if (mUseMasterVolume) {
541                service.adjustMasterVolume(direction, flags);
542            } else {
543                service.adjustStreamVolume(streamType, direction, flags);
544            }
545        } catch (RemoteException e) {
546            Log.e(TAG, "Dead object in adjustStreamVolume", e);
547        }
548    }
549
550    /**
551     * Adjusts the volume of the most relevant stream. For example, if a call is
552     * active, it will have the highest priority regardless of if the in-call
553     * screen is showing. Another example, if music is playing in the background
554     * and a call is not active, the music stream will be adjusted.
555     * <p>
556     * This method should only be used by applications that replace the platform-wide
557     * management of audio settings or the main telephony application.
558     *
559     * @param direction The direction to adjust the volume. One of
560     *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
561     *            {@link #ADJUST_SAME}.
562     * @param flags One or more flags.
563     * @see #adjustSuggestedStreamVolume(int, int, int)
564     * @see #adjustStreamVolume(int, int, int)
565     * @see #setStreamVolume(int, int, int)
566     */
567    public void adjustVolume(int direction, int flags) {
568        IAudioService service = getService();
569        try {
570            if (mUseMasterVolume) {
571                service.adjustMasterVolume(direction, flags);
572            } else {
573                service.adjustVolume(direction, flags);
574            }
575        } catch (RemoteException e) {
576            Log.e(TAG, "Dead object in adjustVolume", e);
577        }
578    }
579
580    /**
581     * Adjusts the volume of the most relevant stream, or the given fallback
582     * stream.
583     * <p>
584     * This method should only be used by applications that replace the platform-wide
585     * management of audio settings or the main telephony application.
586     *
587     * @param direction The direction to adjust the volume. One of
588     *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
589     *            {@link #ADJUST_SAME}.
590     * @param suggestedStreamType The stream type that will be used if there
591     *            isn't a relevant stream. {@link #USE_DEFAULT_STREAM_TYPE} is valid here.
592     * @param flags One or more flags.
593     * @see #adjustVolume(int, int)
594     * @see #adjustStreamVolume(int, int, int)
595     * @see #setStreamVolume(int, int, int)
596     */
597    public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
598        IAudioService service = getService();
599        try {
600            if (mUseMasterVolume) {
601                service.adjustMasterVolume(direction, flags);
602            } else {
603                service.adjustSuggestedStreamVolume(direction, suggestedStreamType, flags);
604            }
605        } catch (RemoteException e) {
606            Log.e(TAG, "Dead object in adjustSuggestedStreamVolume", e);
607        }
608    }
609
610    /**
611     * Adjusts the master volume for the device's audio amplifier.
612     * <p>
613     *
614     * @param steps The number of volume steps to adjust. A positive
615     *            value will raise the volume.
616     * @param flags One or more flags.
617     * @hide
618     */
619    public void adjustMasterVolume(int steps, int flags) {
620        IAudioService service = getService();
621        try {
622            service.adjustMasterVolume(steps, flags);
623        } catch (RemoteException e) {
624            Log.e(TAG, "Dead object in adjustMasterVolume", e);
625        }
626    }
627
628    /**
629     * Returns the current ringtone mode.
630     *
631     * @return The current ringtone mode, one of {@link #RINGER_MODE_NORMAL},
632     *         {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
633     * @see #setRingerMode(int)
634     */
635    public int getRingerMode() {
636        IAudioService service = getService();
637        try {
638            return service.getRingerMode();
639        } catch (RemoteException e) {
640            Log.e(TAG, "Dead object in getRingerMode", e);
641            return RINGER_MODE_NORMAL;
642        }
643    }
644
645    /**
646     * Checks valid ringer mode values.
647     *
648     * @return true if the ringer mode indicated is valid, false otherwise.
649     *
650     * @see #setRingerMode(int)
651     * @hide
652     */
653    public static boolean isValidRingerMode(int ringerMode) {
654        if (ringerMode < 0 || ringerMode > RINGER_MODE_MAX) {
655            return false;
656        }
657        return true;
658    }
659
660    /**
661     * Returns the maximum volume index for a particular stream.
662     *
663     * @param streamType The stream type whose maximum volume index is returned.
664     * @return The maximum valid volume index for the stream.
665     * @see #getStreamVolume(int)
666     */
667    public int getStreamMaxVolume(int streamType) {
668        IAudioService service = getService();
669        try {
670            if (mUseMasterVolume) {
671                return service.getMasterMaxVolume();
672            } else {
673                return service.getStreamMaxVolume(streamType);
674            }
675        } catch (RemoteException e) {
676            Log.e(TAG, "Dead object in getStreamMaxVolume", e);
677            return 0;
678        }
679    }
680
681    /**
682     * Returns the current volume index for a particular stream.
683     *
684     * @param streamType The stream type whose volume index is returned.
685     * @return The current volume index for the stream.
686     * @see #getStreamMaxVolume(int)
687     * @see #setStreamVolume(int, int, int)
688     */
689    public int getStreamVolume(int streamType) {
690        IAudioService service = getService();
691        try {
692            if (mUseMasterVolume) {
693                return service.getMasterVolume();
694            } else {
695                return service.getStreamVolume(streamType);
696            }
697        } catch (RemoteException e) {
698            Log.e(TAG, "Dead object in getStreamVolume", e);
699            return 0;
700        }
701    }
702
703    /**
704     * Get last audible volume before stream was muted.
705     *
706     * @hide
707     */
708    public int getLastAudibleStreamVolume(int streamType) {
709        IAudioService service = getService();
710        try {
711            if (mUseMasterVolume) {
712                return service.getLastAudibleMasterVolume();
713            } else {
714                return service.getLastAudibleStreamVolume(streamType);
715            }
716        } catch (RemoteException e) {
717            Log.e(TAG, "Dead object in getLastAudibleStreamVolume", e);
718            return 0;
719        }
720    }
721
722    /**
723     * Get the stream type whose volume is driving the UI sounds volume.
724     * UI sounds are screen lock/unlock, camera shutter, key clicks...
725     * @hide
726     */
727    public int getMasterStreamType() {
728        IAudioService service = getService();
729        try {
730            return service.getMasterStreamType();
731        } catch (RemoteException e) {
732            Log.e(TAG, "Dead object in getMasterStreamType", e);
733            return STREAM_RING;
734        }
735    }
736
737    /**
738     * Sets the ringer mode.
739     * <p>
740     * Silent mode will mute the volume and will not vibrate. Vibrate mode will
741     * mute the volume and vibrate. Normal mode will be audible and may vibrate
742     * according to user settings.
743     *
744     * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},
745     *            {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
746     * @see #getRingerMode()
747     */
748    public void setRingerMode(int ringerMode) {
749        if (!isValidRingerMode(ringerMode)) {
750            return;
751        }
752        IAudioService service = getService();
753        try {
754            service.setRingerMode(ringerMode);
755        } catch (RemoteException e) {
756            Log.e(TAG, "Dead object in setRingerMode", e);
757        }
758    }
759
760    /**
761     * Sets the volume index for a particular stream.
762     *
763     * @param streamType The stream whose volume index should be set.
764     * @param index The volume index to set. See
765     *            {@link #getStreamMaxVolume(int)} for the largest valid value.
766     * @param flags One or more flags.
767     * @see #getStreamMaxVolume(int)
768     * @see #getStreamVolume(int)
769     */
770    public void setStreamVolume(int streamType, int index, int flags) {
771        IAudioService service = getService();
772        try {
773            if (mUseMasterVolume) {
774                service.setMasterVolume(index, flags);
775            } else {
776                service.setStreamVolume(streamType, index, flags);
777            }
778        } catch (RemoteException e) {
779            Log.e(TAG, "Dead object in setStreamVolume", e);
780        }
781    }
782
783    /**
784     * Returns the maximum volume index for master volume.
785     *
786     * @hide
787     */
788    public int getMasterMaxVolume() {
789        IAudioService service = getService();
790        try {
791            return service.getMasterMaxVolume();
792        } catch (RemoteException e) {
793            Log.e(TAG, "Dead object in getMasterMaxVolume", e);
794            return 0;
795        }
796    }
797
798    /**
799     * Returns the current volume index for master volume.
800     *
801     * @return The current volume index for master volume.
802     * @hide
803     */
804    public int getMasterVolume() {
805        IAudioService service = getService();
806        try {
807            return service.getMasterVolume();
808        } catch (RemoteException e) {
809            Log.e(TAG, "Dead object in getMasterVolume", e);
810            return 0;
811        }
812    }
813
814    /**
815     * Get last audible volume before master volume was muted.
816     *
817     * @hide
818     */
819    public int getLastAudibleMasterVolume() {
820        IAudioService service = getService();
821        try {
822            return service.getLastAudibleMasterVolume();
823        } catch (RemoteException e) {
824            Log.e(TAG, "Dead object in getLastAudibleMasterVolume", e);
825            return 0;
826        }
827    }
828
829    /**
830     * Sets the volume index for master volume.
831     *
832     * @param index The volume index to set. See
833     *            {@link #getMasterMaxVolume(int)} for the largest valid value.
834     * @param flags One or more flags.
835     * @see #getMasterMaxVolume(int)
836     * @see #getMasterVolume(int)
837     * @hide
838     */
839    public void setMasterVolume(int index, int flags) {
840        IAudioService service = getService();
841        try {
842            service.setMasterVolume(index, flags);
843        } catch (RemoteException e) {
844            Log.e(TAG, "Dead object in setMasterVolume", e);
845        }
846    }
847
848    /**
849     * Solo or unsolo a particular stream. All other streams are muted.
850     * <p>
851     * The solo command is protected against client process death: if a process
852     * with an active solo request on a stream dies, all streams that were muted
853     * because of this request will be unmuted automatically.
854     * <p>
855     * The solo requests for a given stream are cumulative: the AudioManager
856     * can receive several solo requests from one or more clients and the stream
857     * will be unsoloed only when the same number of unsolo requests are received.
858     * <p>
859     * For a better user experience, applications MUST unsolo a soloed stream
860     * in onPause() and solo is again in onResume() if appropriate.
861     *
862     * @param streamType The stream to be soloed/unsoloed.
863     * @param state The required solo state: true for solo ON, false for solo OFF
864     */
865    public void setStreamSolo(int streamType, boolean state) {
866        IAudioService service = getService();
867        try {
868            service.setStreamSolo(streamType, state, mICallBack);
869        } catch (RemoteException e) {
870            Log.e(TAG, "Dead object in setStreamSolo", e);
871        }
872    }
873
874    /**
875     * Mute or unmute an audio stream.
876     * <p>
877     * The mute command is protected against client process death: if a process
878     * with an active mute request on a stream dies, this stream will be unmuted
879     * automatically.
880     * <p>
881     * The mute requests for a given stream are cumulative: the AudioManager
882     * can receive several mute requests from one or more clients and the stream
883     * will be unmuted only when the same number of unmute requests are received.
884     * <p>
885     * For a better user experience, applications MUST unmute a muted stream
886     * in onPause() and mute is again in onResume() if appropriate.
887     * <p>
888     * This method should only be used by applications that replace the platform-wide
889     * management of audio settings or the main telephony application.
890     *
891     * @param streamType The stream to be muted/unmuted.
892     * @param state The required mute state: true for mute ON, false for mute OFF
893     */
894    public void setStreamMute(int streamType, boolean state) {
895        IAudioService service = getService();
896        try {
897            service.setStreamMute(streamType, state, mICallBack);
898        } catch (RemoteException e) {
899            Log.e(TAG, "Dead object in setStreamMute", e);
900        }
901    }
902
903    /**
904     * get stream mute state.
905     *
906     * @hide
907     */
908    public boolean isStreamMute(int streamType) {
909        IAudioService service = getService();
910        try {
911            return service.isStreamMute(streamType);
912        } catch (RemoteException e) {
913            Log.e(TAG, "Dead object in isStreamMute", e);
914            return false;
915        }
916    }
917
918    /**
919     * set master mute state.
920     *
921     * @hide
922     */
923    public void setMasterMute(boolean state) {
924        setMasterMute(state, FLAG_SHOW_UI);
925    }
926
927    /**
928     * set master mute state with optional flags.
929     *
930     * @hide
931     */
932    public void setMasterMute(boolean state, int flags) {
933        IAudioService service = getService();
934        try {
935            service.setMasterMute(state, flags, mICallBack);
936        } catch (RemoteException e) {
937            Log.e(TAG, "Dead object in setMasterMute", e);
938        }
939    }
940
941    /**
942     * get master mute state.
943     *
944     * @hide
945     */
946    public boolean isMasterMute() {
947        IAudioService service = getService();
948        try {
949            return service.isMasterMute();
950        } catch (RemoteException e) {
951            Log.e(TAG, "Dead object in isMasterMute", e);
952            return false;
953        }
954    }
955
956    /**
957     * forces the stream controlled by hard volume keys
958     * specifying streamType == -1 releases control to the
959     * logic.
960     *
961     * @hide
962     */
963    public void forceVolumeControlStream(int streamType) {
964        IAudioService service = getService();
965        try {
966            service.forceVolumeControlStream(streamType, mICallBack);
967        } catch (RemoteException e) {
968            Log.e(TAG, "Dead object in forceVolumeControlStream", e);
969        }
970    }
971
972    /**
973     * Returns whether a particular type should vibrate according to user
974     * settings and the current ringer mode.
975     * <p>
976     * This shouldn't be needed by most clients that use notifications to
977     * vibrate. The notification manager will not vibrate if the policy doesn't
978     * allow it, so the client should always set a vibrate pattern and let the
979     * notification manager control whether or not to actually vibrate.
980     *
981     * @param vibrateType The type of vibrate. One of
982     *            {@link #VIBRATE_TYPE_NOTIFICATION} or
983     *            {@link #VIBRATE_TYPE_RINGER}.
984     * @return Whether the type should vibrate at the instant this method is
985     *         called.
986     * @see #setVibrateSetting(int, int)
987     * @see #getVibrateSetting(int)
988     * @deprecated Applications should maintain their own vibrate policy based on
989     * current ringer mode that can be queried via {@link #getRingerMode()}.
990     */
991    public boolean shouldVibrate(int vibrateType) {
992        IAudioService service = getService();
993        try {
994            return service.shouldVibrate(vibrateType);
995        } catch (RemoteException e) {
996            Log.e(TAG, "Dead object in shouldVibrate", e);
997            return false;
998        }
999    }
1000
1001    /**
1002     * Returns whether the user's vibrate setting for a vibrate type.
1003     * <p>
1004     * This shouldn't be needed by most clients that want to vibrate, instead
1005     * see {@link #shouldVibrate(int)}.
1006     *
1007     * @param vibrateType The type of vibrate. One of
1008     *            {@link #VIBRATE_TYPE_NOTIFICATION} or
1009     *            {@link #VIBRATE_TYPE_RINGER}.
1010     * @return The vibrate setting, one of {@link #VIBRATE_SETTING_ON},
1011     *         {@link #VIBRATE_SETTING_OFF}, or
1012     *         {@link #VIBRATE_SETTING_ONLY_SILENT}.
1013     * @see #setVibrateSetting(int, int)
1014     * @see #shouldVibrate(int)
1015     * @deprecated Applications should maintain their own vibrate policy based on
1016     * current ringer mode that can be queried via {@link #getRingerMode()}.
1017     */
1018    public int getVibrateSetting(int vibrateType) {
1019        IAudioService service = getService();
1020        try {
1021            return service.getVibrateSetting(vibrateType);
1022        } catch (RemoteException e) {
1023            Log.e(TAG, "Dead object in getVibrateSetting", e);
1024            return VIBRATE_SETTING_OFF;
1025        }
1026    }
1027
1028    /**
1029     * Sets the setting for when the vibrate type should vibrate.
1030     * <p>
1031     * This method should only be used by applications that replace the platform-wide
1032     * management of audio settings or the main telephony application.
1033     *
1034     * @param vibrateType The type of vibrate. One of
1035     *            {@link #VIBRATE_TYPE_NOTIFICATION} or
1036     *            {@link #VIBRATE_TYPE_RINGER}.
1037     * @param vibrateSetting The vibrate setting, one of
1038     *            {@link #VIBRATE_SETTING_ON},
1039     *            {@link #VIBRATE_SETTING_OFF}, or
1040     *            {@link #VIBRATE_SETTING_ONLY_SILENT}.
1041     * @see #getVibrateSetting(int)
1042     * @see #shouldVibrate(int)
1043     * @deprecated Applications should maintain their own vibrate policy based on
1044     * current ringer mode that can be queried via {@link #getRingerMode()}.
1045     */
1046    public void setVibrateSetting(int vibrateType, int vibrateSetting) {
1047        IAudioService service = getService();
1048        try {
1049            service.setVibrateSetting(vibrateType, vibrateSetting);
1050        } catch (RemoteException e) {
1051            Log.e(TAG, "Dead object in setVibrateSetting", e);
1052        }
1053    }
1054
1055    /**
1056     * Sets the speakerphone on or off.
1057     * <p>
1058     * This method should only be used by applications that replace the platform-wide
1059     * management of audio settings or the main telephony application.
1060     *
1061     * @param on set <var>true</var> to turn on speakerphone;
1062     *           <var>false</var> to turn it off
1063     */
1064    public void setSpeakerphoneOn(boolean on){
1065        IAudioService service = getService();
1066        try {
1067            service.setSpeakerphoneOn(on);
1068        } catch (RemoteException e) {
1069            Log.e(TAG, "Dead object in setSpeakerphoneOn", e);
1070        }
1071    }
1072
1073    /**
1074     * Checks whether the speakerphone is on or off.
1075     *
1076     * @return true if speakerphone is on, false if it's off
1077     */
1078    public boolean isSpeakerphoneOn() {
1079        IAudioService service = getService();
1080        try {
1081            return service.isSpeakerphoneOn();
1082        } catch (RemoteException e) {
1083            Log.e(TAG, "Dead object in isSpeakerphoneOn", e);
1084            return false;
1085        }
1086     }
1087
1088    //====================================================================
1089    // Bluetooth SCO control
1090    /**
1091     * Sticky broadcast intent action indicating that the bluetoooth SCO audio
1092     * connection state has changed. The intent contains on extra {@link #EXTRA_SCO_AUDIO_STATE}
1093     * indicating the new state which is either {@link #SCO_AUDIO_STATE_DISCONNECTED}
1094     * or {@link #SCO_AUDIO_STATE_CONNECTED}
1095     *
1096     * @see #startBluetoothSco()
1097     * @deprecated Use  {@link #ACTION_SCO_AUDIO_STATE_UPDATED} instead
1098     */
1099    @Deprecated
1100    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1101    public static final String ACTION_SCO_AUDIO_STATE_CHANGED =
1102            "android.media.SCO_AUDIO_STATE_CHANGED";
1103
1104     /**
1105     * Sticky broadcast intent action indicating that the bluetoooth SCO audio
1106     * connection state has been updated.
1107     * <p>This intent has two extras:
1108     * <ul>
1109     *   <li> {@link #EXTRA_SCO_AUDIO_STATE} - The new SCO audio state. </li>
1110     *   <li> {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}- The previous SCO audio state. </li>
1111     * </ul>
1112     * <p> EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE can be any of:
1113     * <ul>
1114     *   <li> {@link #SCO_AUDIO_STATE_DISCONNECTED}, </li>
1115     *   <li> {@link #SCO_AUDIO_STATE_CONNECTING} or </li>
1116     *   <li> {@link #SCO_AUDIO_STATE_CONNECTED}, </li>
1117     * </ul>
1118     * @see #startBluetoothSco()
1119     */
1120    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1121    public static final String ACTION_SCO_AUDIO_STATE_UPDATED =
1122            "android.media.ACTION_SCO_AUDIO_STATE_UPDATED";
1123
1124    /**
1125     * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_CHANGED} or
1126     * {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the new bluetooth SCO connection state.
1127     */
1128    public static final String EXTRA_SCO_AUDIO_STATE =
1129            "android.media.extra.SCO_AUDIO_STATE";
1130
1131    /**
1132     * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the previous
1133     * bluetooth SCO connection state.
1134     */
1135    public static final String EXTRA_SCO_AUDIO_PREVIOUS_STATE =
1136            "android.media.extra.SCO_AUDIO_PREVIOUS_STATE";
1137
1138    /**
1139     * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
1140     * indicating that the SCO audio channel is not established
1141     */
1142    public static final int SCO_AUDIO_STATE_DISCONNECTED = 0;
1143    /**
1144     * Value for extra {@link #EXTRA_SCO_AUDIO_STATE} or {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}
1145     * indicating that the SCO audio channel is established
1146     */
1147    public static final int SCO_AUDIO_STATE_CONNECTED = 1;
1148    /**
1149     * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
1150     * indicating that the SCO audio channel is being established
1151     */
1152    public static final int SCO_AUDIO_STATE_CONNECTING = 2;
1153    /**
1154     * Value for extra EXTRA_SCO_AUDIO_STATE indicating that
1155     * there was an error trying to obtain the state
1156     */
1157    public static final int SCO_AUDIO_STATE_ERROR = -1;
1158
1159
1160    /**
1161     * Indicates if current platform supports use of SCO for off call use cases.
1162     * Application wanted to use bluetooth SCO audio when the phone is not in call
1163     * must first call thsi method to make sure that the platform supports this
1164     * feature.
1165     * @return true if bluetooth SCO can be used for audio when not in call
1166     *         false otherwise
1167     * @see #startBluetoothSco()
1168    */
1169    public boolean isBluetoothScoAvailableOffCall() {
1170        return mContext.getResources().getBoolean(
1171               com.android.internal.R.bool.config_bluetooth_sco_off_call);
1172    }
1173
1174    /**
1175     * Start bluetooth SCO audio connection.
1176     * <p>Requires Permission:
1177     *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1178     * <p>This method can be used by applications wanting to send and received audio
1179     * to/from a bluetooth SCO headset while the phone is not in call.
1180     * <p>As the SCO connection establishment can take several seconds,
1181     * applications should not rely on the connection to be available when the method
1182     * returns but instead register to receive the intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED}
1183     * and wait for the state to be {@link #SCO_AUDIO_STATE_CONNECTED}.
1184     * <p>As the ACTION_SCO_AUDIO_STATE_UPDATED intent is sticky, the application can check the SCO
1185     * audio state before calling startBluetoothSco() by reading the intent returned by the receiver
1186     * registration. If the state is already CONNECTED, no state change will be received via the
1187     * intent after calling startBluetoothSco(). It is however useful to call startBluetoothSco()
1188     * so that the connection stays active in case the current initiator stops the connection.
1189     * <p>Unless the connection is already active as described above, the state will always
1190     * transition from DISCONNECTED to CONNECTING and then either to CONNECTED if the connection
1191     * succeeds or back to DISCONNECTED if the connection fails (e.g no headset is connected).
1192     * <p>When finished with the SCO connection or if the establishment fails, the application must
1193     * call {@link #stopBluetoothSco()} to clear the request and turn down the bluetooth connection.
1194     * <p>Even if a SCO connection is established, the following restrictions apply on audio
1195     * output streams so that they can be routed to SCO headset:
1196     * <ul>
1197     *   <li> the stream type must be {@link #STREAM_VOICE_CALL} </li>
1198     *   <li> the format must be mono </li>
1199     *   <li> the sampling must be 16kHz or 8kHz </li>
1200     * </ul>
1201     * <p>The following restrictions apply on input streams:
1202     * <ul>
1203     *   <li> the format must be mono </li>
1204     *   <li> the sampling must be 8kHz </li>
1205     * </ul>
1206     * <p>Note that the phone application always has the priority on the usage of the SCO
1207     * connection for telephony. If this method is called while the phone is in call
1208     * it will be ignored. Similarly, if a call is received or sent while an application
1209     * is using the SCO connection, the connection will be lost for the application and NOT
1210     * returned automatically when the call ends.
1211     * @see #stopBluetoothSco()
1212     * @see #ACTION_SCO_AUDIO_STATE_UPDATED
1213     */
1214    public void startBluetoothSco(){
1215        IAudioService service = getService();
1216        try {
1217            service.startBluetoothSco(mICallBack);
1218        } catch (RemoteException e) {
1219            Log.e(TAG, "Dead object in startBluetoothSco", e);
1220        }
1221    }
1222
1223    /**
1224     * Stop bluetooth SCO audio connection.
1225     * <p>Requires Permission:
1226     *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1227     * <p>This method must be called by applications having requested the use of
1228     * bluetooth SCO audio with {@link #startBluetoothSco()}
1229     * when finished with the SCO connection or if connection fails.
1230     * @see #startBluetoothSco()
1231     */
1232    public void stopBluetoothSco(){
1233        IAudioService service = getService();
1234        try {
1235            service.stopBluetoothSco(mICallBack);
1236        } catch (RemoteException e) {
1237            Log.e(TAG, "Dead object in stopBluetoothSco", e);
1238        }
1239    }
1240
1241    /**
1242     * Request use of Bluetooth SCO headset for communications.
1243     * <p>
1244     * This method should only be used by applications that replace the platform-wide
1245     * management of audio settings or the main telephony application.
1246     *
1247     * @param on set <var>true</var> to use bluetooth SCO for communications;
1248     *               <var>false</var> to not use bluetooth SCO for communications
1249     */
1250    public void setBluetoothScoOn(boolean on){
1251        IAudioService service = getService();
1252        try {
1253            service.setBluetoothScoOn(on);
1254        } catch (RemoteException e) {
1255            Log.e(TAG, "Dead object in setBluetoothScoOn", e);
1256        }
1257    }
1258
1259    /**
1260     * Checks whether communications use Bluetooth SCO.
1261     *
1262     * @return true if SCO is used for communications;
1263     *         false if otherwise
1264     */
1265    public boolean isBluetoothScoOn() {
1266        IAudioService service = getService();
1267        try {
1268            return service.isBluetoothScoOn();
1269        } catch (RemoteException e) {
1270            Log.e(TAG, "Dead object in isBluetoothScoOn", e);
1271            return false;
1272        }
1273    }
1274
1275    /**
1276     * Allow or disallow use of Bluetooth A2DP for media.
1277     * <p>The default behavior of the system is to use A2DP for media playback whenever an A2DP sink
1278     * is connected. Applications can use this method to override this behavior.
1279     * Note that the request will not persist after a wired headset or an A2DP sink is connected or
1280     * disconnected:
1281     * - Connection of an A2DP sink automatically enables use of A2DP.
1282     * - Connection of a wired headset automatically disables use of A2DP.
1283     * - Disconnection of a wired headset automatically enables use of A2DP if an A2DP sink is
1284     * connected.
1285     * <p>Requires Permission:
1286     *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1287     * @param on set <var>true</var> to allow use of A2DP for media (default).
1288     *               <var>false</var> to disallow use of A2DP for media.
1289     * @deprecated Do not use.
1290     */
1291    @Deprecated public void setBluetoothA2dpOn(boolean on){
1292        IAudioService service = getService();
1293        try {
1294            service.setBluetoothA2dpOn(on);
1295        } catch (RemoteException e) {
1296            Log.e(TAG, "Dead object in setBluetoothA2dpOn", e);
1297        }
1298    }
1299
1300    /**
1301     * Checks whether use of A2DP sinks is enabled for media.
1302     *
1303     * @return true if use of A2DP is enabled for media, false otherwise.
1304     */
1305    public boolean isBluetoothA2dpOn() {
1306        IAudioService service = getService();
1307        try {
1308            return service.isBluetoothA2dpOn();
1309        } catch (RemoteException e) {
1310            Log.e(TAG, "Dead object in isBluetoothA2dpOn", e);
1311            return false;
1312        }
1313    }
1314
1315    /**
1316     * Sets audio routing to the wired headset on or off.
1317     *
1318     * @param on set <var>true</var> to route audio to/from wired
1319     *           headset; <var>false</var> disable wired headset audio
1320     * @deprecated Do not use.
1321     */
1322    @Deprecated public void setWiredHeadsetOn(boolean on){
1323    }
1324
1325    /**
1326     * Checks whether a wired headset is connected or not.
1327     * <p>This is not a valid indication that audio playback is
1328     * actually over the wired headset as audio routing depends on other conditions.
1329     *
1330     * @return true if a wired headset is connected.
1331     *         false if otherwise
1332     * @deprecated Use only to check is a headset is connected or not.
1333     */
1334    public boolean isWiredHeadsetOn() {
1335        if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADSET,"")
1336                == AudioSystem.DEVICE_STATE_UNAVAILABLE &&
1337            AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE,"")
1338                == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
1339            return false;
1340        } else {
1341            return true;
1342        }
1343    }
1344
1345    /**
1346     * Sets the microphone mute on or off.
1347     * <p>
1348     * This method should only be used by applications that replace the platform-wide
1349     * management of audio settings or the main telephony application.
1350     *
1351     * @param on set <var>true</var> to mute the microphone;
1352     *           <var>false</var> to turn mute off
1353     */
1354    public void setMicrophoneMute(boolean on){
1355        AudioSystem.muteMicrophone(on);
1356    }
1357
1358    /**
1359     * Checks whether the microphone mute is on or off.
1360     *
1361     * @return true if microphone is muted, false if it's not
1362     */
1363    public boolean isMicrophoneMute() {
1364        return AudioSystem.isMicrophoneMuted();
1365    }
1366
1367    /**
1368     * Sets the audio mode.
1369     * <p>
1370     * The audio mode encompasses audio routing AND the behavior of
1371     * the telephony layer. Therefore this method should only be used by applications that
1372     * replace the platform-wide management of audio settings or the main telephony application.
1373     * In particular, the {@link #MODE_IN_CALL} mode should only be used by the telephony
1374     * application when it places a phone call, as it will cause signals from the radio layer
1375     * to feed the platform mixer.
1376     *
1377     * @param mode  the requested audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
1378     *              {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
1379     *              Informs the HAL about the current audio state so that
1380     *              it can route the audio appropriately.
1381     */
1382    public void setMode(int mode) {
1383        IAudioService service = getService();
1384        try {
1385            service.setMode(mode, mICallBack);
1386        } catch (RemoteException e) {
1387            Log.e(TAG, "Dead object in setMode", e);
1388        }
1389    }
1390
1391    /**
1392     * Returns the current audio mode.
1393     *
1394     * @return      the current audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
1395     *              {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
1396     *              Returns the current current audio state from the HAL.
1397     */
1398    public int getMode() {
1399        IAudioService service = getService();
1400        try {
1401            return service.getMode();
1402        } catch (RemoteException e) {
1403            Log.e(TAG, "Dead object in getMode", e);
1404            return MODE_INVALID;
1405        }
1406    }
1407
1408    /* modes for setMode/getMode/setRoute/getRoute */
1409    /**
1410     * Audio harware modes.
1411     */
1412    /**
1413     * Invalid audio mode.
1414     */
1415    public static final int MODE_INVALID            = AudioSystem.MODE_INVALID;
1416    /**
1417     * Current audio mode. Used to apply audio routing to current mode.
1418     */
1419    public static final int MODE_CURRENT            = AudioSystem.MODE_CURRENT;
1420    /**
1421     * Normal audio mode: not ringing and no call established.
1422     */
1423    public static final int MODE_NORMAL             = AudioSystem.MODE_NORMAL;
1424    /**
1425     * Ringing audio mode. An incoming is being signaled.
1426     */
1427    public static final int MODE_RINGTONE           = AudioSystem.MODE_RINGTONE;
1428    /**
1429     * In call audio mode. A telephony call is established.
1430     */
1431    public static final int MODE_IN_CALL            = AudioSystem.MODE_IN_CALL;
1432    /**
1433     * In communication audio mode. An audio/video chat or VoIP call is established.
1434     */
1435    public static final int MODE_IN_COMMUNICATION   = AudioSystem.MODE_IN_COMMUNICATION;
1436
1437    /* Routing bits for setRouting/getRouting API */
1438    /**
1439     * Routing audio output to earpiece
1440     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1441     * setBluetoothScoOn() methods instead.
1442     */
1443    @Deprecated public static final int ROUTE_EARPIECE          = AudioSystem.ROUTE_EARPIECE;
1444    /**
1445     * Routing audio output to speaker
1446     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1447     * setBluetoothScoOn() methods instead.
1448     */
1449    @Deprecated public static final int ROUTE_SPEAKER           = AudioSystem.ROUTE_SPEAKER;
1450    /**
1451     * @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
1452     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1453     * setBluetoothScoOn() methods instead.
1454     */
1455    @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
1456    /**
1457     * Routing audio output to bluetooth SCO
1458     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1459     * setBluetoothScoOn() methods instead.
1460     */
1461    @Deprecated public static final int ROUTE_BLUETOOTH_SCO     = AudioSystem.ROUTE_BLUETOOTH_SCO;
1462    /**
1463     * Routing audio output to headset
1464     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1465     * setBluetoothScoOn() methods instead.
1466     */
1467    @Deprecated public static final int ROUTE_HEADSET           = AudioSystem.ROUTE_HEADSET;
1468    /**
1469     * Routing audio output to bluetooth A2DP
1470     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1471     * setBluetoothScoOn() methods instead.
1472     */
1473    @Deprecated public static final int ROUTE_BLUETOOTH_A2DP    = AudioSystem.ROUTE_BLUETOOTH_A2DP;
1474    /**
1475     * Used for mask parameter of {@link #setRouting(int,int,int)}.
1476     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1477     * setBluetoothScoOn() methods instead.
1478     */
1479    @Deprecated public static final int ROUTE_ALL               = AudioSystem.ROUTE_ALL;
1480
1481    /**
1482     * Sets the audio routing for a specified mode
1483     *
1484     * @param mode   audio mode to change route. E.g., MODE_RINGTONE.
1485     * @param routes bit vector of routes requested, created from one or
1486     *               more of ROUTE_xxx types. Set bits indicate that route should be on
1487     * @param mask   bit vector of routes to change, created from one or more of
1488     * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
1489     *
1490     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1491     * setBluetoothScoOn() methods instead.
1492     */
1493    @Deprecated
1494    public void setRouting(int mode, int routes, int mask) {
1495    }
1496
1497    /**
1498     * Returns the current audio routing bit vector for a specified mode.
1499     *
1500     * @param mode audio mode to get route (e.g., MODE_RINGTONE)
1501     * @return an audio route bit vector that can be compared with ROUTE_xxx
1502     * bits
1503     * @deprecated   Do not query audio routing directly, use isSpeakerphoneOn(),
1504     * isBluetoothScoOn(), isBluetoothA2dpOn() and isWiredHeadsetOn() methods instead.
1505     */
1506    @Deprecated
1507    public int getRouting(int mode) {
1508        return -1;
1509    }
1510
1511    /**
1512     * Checks whether any music is active.
1513     *
1514     * @return true if any music tracks are active.
1515     */
1516    public boolean isMusicActive() {
1517        return AudioSystem.isStreamActive(STREAM_MUSIC, 0);
1518    }
1519
1520    /*
1521     * Sets a generic audio configuration parameter. The use of these parameters
1522     * are platform dependant, see libaudio
1523     *
1524     * ** Temporary interface - DO NOT USE
1525     *
1526     * TODO: Replace with a more generic key:value get/set mechanism
1527     *
1528     * param key   name of parameter to set. Must not be null.
1529     * param value value of parameter. Must not be null.
1530     */
1531    /**
1532     * @hide
1533     * @deprecated Use {@link #setPrameters(String)} instead
1534     */
1535    @Deprecated public void setParameter(String key, String value) {
1536        setParameters(key+"="+value);
1537    }
1538
1539    /**
1540     * Sets a variable number of parameter values to audio hardware.
1541     *
1542     * @param keyValuePairs list of parameters key value pairs in the form:
1543     *    key1=value1;key2=value2;...
1544     *
1545     */
1546    public void setParameters(String keyValuePairs) {
1547        AudioSystem.setParameters(keyValuePairs);
1548    }
1549
1550    /**
1551     * Sets a varaible number of parameter values to audio hardware.
1552     *
1553     * @param keys list of parameters
1554     * @return list of parameters key value pairs in the form:
1555     *    key1=value1;key2=value2;...
1556     */
1557    public String getParameters(String keys) {
1558        return AudioSystem.getParameters(keys);
1559    }
1560
1561    /* Sound effect identifiers */
1562    /**
1563     * Keyboard and direction pad click sound
1564     * @see #playSoundEffect(int)
1565     */
1566    public static final int FX_KEY_CLICK = 0;
1567    /**
1568     * Focus has moved up
1569     * @see #playSoundEffect(int)
1570     */
1571    public static final int FX_FOCUS_NAVIGATION_UP = 1;
1572    /**
1573     * Focus has moved down
1574     * @see #playSoundEffect(int)
1575     */
1576    public static final int FX_FOCUS_NAVIGATION_DOWN = 2;
1577    /**
1578     * Focus has moved left
1579     * @see #playSoundEffect(int)
1580     */
1581    public static final int FX_FOCUS_NAVIGATION_LEFT = 3;
1582    /**
1583     * Focus has moved right
1584     * @see #playSoundEffect(int)
1585     */
1586    public static final int FX_FOCUS_NAVIGATION_RIGHT = 4;
1587    /**
1588     * IME standard keypress sound
1589     * @see #playSoundEffect(int)
1590     */
1591    public static final int FX_KEYPRESS_STANDARD = 5;
1592    /**
1593     * IME spacebar keypress sound
1594     * @see #playSoundEffect(int)
1595     */
1596    public static final int FX_KEYPRESS_SPACEBAR = 6;
1597    /**
1598     * IME delete keypress sound
1599     * @see #playSoundEffect(int)
1600     */
1601    public static final int FX_KEYPRESS_DELETE = 7;
1602    /**
1603     * IME return_keypress sound
1604     * @see #playSoundEffect(int)
1605     */
1606    public static final int FX_KEYPRESS_RETURN = 8;
1607    /**
1608     * @hide Number of sound effects
1609     */
1610    public static final int NUM_SOUND_EFFECTS = 9;
1611
1612    /**
1613     * Plays a sound effect (Key clicks, lid open/close...)
1614     * @param effectType The type of sound effect. One of
1615     *            {@link #FX_KEY_CLICK},
1616     *            {@link #FX_FOCUS_NAVIGATION_UP},
1617     *            {@link #FX_FOCUS_NAVIGATION_DOWN},
1618     *            {@link #FX_FOCUS_NAVIGATION_LEFT},
1619     *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
1620     *            {@link #FX_KEYPRESS_STANDARD},
1621     *            {@link #FX_KEYPRESS_SPACEBAR},
1622     *            {@link #FX_KEYPRESS_DELETE},
1623     *            {@link #FX_KEYPRESS_RETURN},
1624     * NOTE: This version uses the UI settings to determine
1625     * whether sounds are heard or not.
1626     */
1627    public void  playSoundEffect(int effectType) {
1628        if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
1629            return;
1630        }
1631
1632        if (!querySoundEffectsEnabled()) {
1633            return;
1634        }
1635
1636        IAudioService service = getService();
1637        try {
1638            service.playSoundEffect(effectType);
1639        } catch (RemoteException e) {
1640            Log.e(TAG, "Dead object in playSoundEffect"+e);
1641        }
1642    }
1643
1644    /**
1645     * Plays a sound effect (Key clicks, lid open/close...)
1646     * @param effectType The type of sound effect. One of
1647     *            {@link #FX_KEY_CLICK},
1648     *            {@link #FX_FOCUS_NAVIGATION_UP},
1649     *            {@link #FX_FOCUS_NAVIGATION_DOWN},
1650     *            {@link #FX_FOCUS_NAVIGATION_LEFT},
1651     *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
1652     *            {@link #FX_KEYPRESS_STANDARD},
1653     *            {@link #FX_KEYPRESS_SPACEBAR},
1654     *            {@link #FX_KEYPRESS_DELETE},
1655     *            {@link #FX_KEYPRESS_RETURN},
1656     * @param volume Sound effect volume.
1657     * The volume value is a raw scalar so UI controls should be scaled logarithmically.
1658     * If a volume of -1 is specified, the AudioManager.STREAM_MUSIC stream volume minus 3dB will be used.
1659     * NOTE: This version is for applications that have their own
1660     * settings panel for enabling and controlling volume.
1661     */
1662    public void  playSoundEffect(int effectType, float volume) {
1663        if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
1664            return;
1665        }
1666
1667        IAudioService service = getService();
1668        try {
1669            service.playSoundEffectVolume(effectType, volume);
1670        } catch (RemoteException e) {
1671            Log.e(TAG, "Dead object in playSoundEffect"+e);
1672        }
1673    }
1674
1675    /**
1676     * Settings has an in memory cache, so this is fast.
1677     */
1678    private boolean querySoundEffectsEnabled() {
1679        return Settings.System.getInt(mContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0) != 0;
1680    }
1681
1682
1683    /**
1684     *  Load Sound effects.
1685     *  This method must be called when sound effects are enabled.
1686     */
1687    public void loadSoundEffects() {
1688        IAudioService service = getService();
1689        try {
1690            service.loadSoundEffects();
1691        } catch (RemoteException e) {
1692            Log.e(TAG, "Dead object in loadSoundEffects"+e);
1693        }
1694    }
1695
1696    /**
1697     *  Unload Sound effects.
1698     *  This method can be called to free some memory when
1699     *  sound effects are disabled.
1700     */
1701    public void unloadSoundEffects() {
1702        IAudioService service = getService();
1703        try {
1704            service.unloadSoundEffects();
1705        } catch (RemoteException e) {
1706            Log.e(TAG, "Dead object in unloadSoundEffects"+e);
1707        }
1708    }
1709
1710    /**
1711     * Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
1712     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
1713     * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
1714     */
1715    public static final int AUDIOFOCUS_GAIN = 1;
1716    /**
1717     * Used to indicate a temporary gain or request of audio focus, anticipated to last a short
1718     * amount of time. Examples of temporary changes are the playback of driving directions, or an
1719     * event notification.
1720     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
1721     * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
1722     */
1723    public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
1724    /**
1725     * Used to indicate a temporary request of audio focus, anticipated to last a short
1726     * amount of time, and where it is acceptable for other audio applications to keep playing
1727     * after having lowered their output level (also referred to as "ducking").
1728     * Examples of temporary changes are the playback of driving directions where playback of music
1729     * in the background is acceptable.
1730     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
1731     * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
1732     */
1733    public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;
1734    /**
1735     * Used to indicate a loss of audio focus of unknown duration.
1736     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
1737     */
1738    public static final int AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN;
1739    /**
1740     * Used to indicate a transient loss of audio focus.
1741     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
1742     */
1743    public static final int AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT;
1744    /**
1745     * Used to indicate a transient loss of audio focus where the loser of the audio focus can
1746     * lower its output volume if it wants to continue playing (also referred to as "ducking"), as
1747     * the new focus owner doesn't require others to be silent.
1748     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
1749     */
1750    public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
1751            -1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
1752
1753    /**
1754     * Interface definition for a callback to be invoked when the audio focus of the system is
1755     * updated.
1756     */
1757    public interface OnAudioFocusChangeListener {
1758        /**
1759         * Called on the listener to notify it the audio focus for this listener has been changed.
1760         * The focusChange value indicates whether the focus was gained,
1761         * whether the focus was lost, and whether that loss is transient, or whether the new focus
1762         * holder will hold it for an unknown amount of time.
1763         * When losing focus, listeners can use the focus change information to decide what
1764         * behavior to adopt when losing focus. A music player could for instance elect to lower
1765         * the volume of its music stream (duck) for transient focus losses, and pause otherwise.
1766         * @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
1767         *   {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
1768         *   and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
1769         */
1770        public void onAudioFocusChange(int focusChange);
1771    }
1772
1773    /**
1774     * Map to convert focus event listener IDs, as used in the AudioService audio focus stack,
1775     * to actual listener objects.
1776     */
1777    private final HashMap<String, OnAudioFocusChangeListener> mAudioFocusIdListenerMap =
1778            new HashMap<String, OnAudioFocusChangeListener>();
1779    /**
1780     * Lock to prevent concurrent changes to the list of focus listeners for this AudioManager
1781     * instance.
1782     */
1783    private final Object mFocusListenerLock = new Object();
1784
1785    private OnAudioFocusChangeListener findFocusListener(String id) {
1786        return mAudioFocusIdListenerMap.get(id);
1787    }
1788
1789    /**
1790     * Handler for audio focus events coming from the audio service.
1791     */
1792    private final FocusEventHandlerDelegate mAudioFocusEventHandlerDelegate =
1793            new FocusEventHandlerDelegate();
1794
1795    /**
1796     * Helper class to handle the forwarding of audio focus events to the appropriate listener
1797     */
1798    private class FocusEventHandlerDelegate {
1799        private final Handler mHandler;
1800
1801        FocusEventHandlerDelegate() {
1802            Looper looper;
1803            if ((looper = Looper.myLooper()) == null) {
1804                looper = Looper.getMainLooper();
1805            }
1806
1807            if (looper != null) {
1808                // implement the event handler delegate to receive audio focus events
1809                mHandler = new Handler(looper) {
1810                    @Override
1811                    public void handleMessage(Message msg) {
1812                        OnAudioFocusChangeListener listener = null;
1813                        synchronized(mFocusListenerLock) {
1814                            listener = findFocusListener((String)msg.obj);
1815                        }
1816                        if (listener != null) {
1817                            listener.onAudioFocusChange(msg.what);
1818                        }
1819                    }
1820                };
1821            } else {
1822                mHandler = null;
1823            }
1824        }
1825
1826        Handler getHandler() {
1827            return mHandler;
1828        }
1829    }
1830
1831    private final IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
1832
1833        public void dispatchAudioFocusChange(int focusChange, String id) {
1834            Message m = mAudioFocusEventHandlerDelegate.getHandler().obtainMessage(focusChange, id);
1835            mAudioFocusEventHandlerDelegate.getHandler().sendMessage(m);
1836        }
1837
1838    };
1839
1840    private String getIdForAudioFocusListener(OnAudioFocusChangeListener l) {
1841        if (l == null) {
1842            return new String(this.toString());
1843        } else {
1844            return new String(this.toString() + l.toString());
1845        }
1846    }
1847
1848    /**
1849     * @hide
1850     * Registers a listener to be called when audio focus changes. Calling this method is optional
1851     * before calling {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, as it
1852     * will register the listener as well if it wasn't registered already.
1853     * @param l the listener to be notified of audio focus changes.
1854     */
1855    public void registerAudioFocusListener(OnAudioFocusChangeListener l) {
1856        synchronized(mFocusListenerLock) {
1857            if (mAudioFocusIdListenerMap.containsKey(getIdForAudioFocusListener(l))) {
1858                return;
1859            }
1860            mAudioFocusIdListenerMap.put(getIdForAudioFocusListener(l), l);
1861        }
1862    }
1863
1864    /**
1865     * @hide
1866     * Causes the specified listener to not be called anymore when focus is gained or lost.
1867     * @param l the listener to unregister.
1868     */
1869    public void unregisterAudioFocusListener(OnAudioFocusChangeListener l) {
1870
1871        // remove locally
1872        synchronized(mFocusListenerLock) {
1873            mAudioFocusIdListenerMap.remove(getIdForAudioFocusListener(l));
1874        }
1875    }
1876
1877
1878    /**
1879     * A failed focus change request.
1880     */
1881    public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
1882    /**
1883     * A successful focus change request.
1884     */
1885    public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
1886
1887
1888    /**
1889     *  Request audio focus.
1890     *  Send a request to obtain the audio focus
1891     *  @param l the listener to be notified of audio focus changes
1892     *  @param streamType the main audio stream type affected by the focus request
1893     *  @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
1894     *      is temporary, and focus will be abandonned shortly. Examples of transient requests are
1895     *      for the playback of driving directions, or notifications sounds.
1896     *      Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
1897     *      the previous focus owner to keep playing if it ducks its audio output.
1898     *      Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
1899     *      as the playback of a song or a video.
1900     *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
1901     */
1902    public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) {
1903        int status = AUDIOFOCUS_REQUEST_FAILED;
1904        if ((durationHint < AUDIOFOCUS_GAIN) || (durationHint > AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK))
1905        {
1906            Log.e(TAG, "Invalid duration hint, audio focus request denied");
1907            return status;
1908        }
1909        registerAudioFocusListener(l);
1910        //TODO protect request by permission check?
1911        IAudioService service = getService();
1912        try {
1913            status = service.requestAudioFocus(streamType, durationHint, mICallBack,
1914                    mAudioFocusDispatcher, getIdForAudioFocusListener(l),
1915                    mContext.getPackageName() /* package name */);
1916        } catch (RemoteException e) {
1917            Log.e(TAG, "Can't call requestAudioFocus() on AudioService due to "+e);
1918        }
1919        return status;
1920    }
1921
1922    /**
1923     * @hide
1924     * Used internally by telephony package to request audio focus. Will cause the focus request
1925     * to be associated with the "voice communication" identifier only used in AudioService
1926     * to identify this use case.
1927     * @param streamType use STREAM_RING for focus requests when ringing, VOICE_CALL for
1928     *    the establishment of the call
1929     * @param durationHint the type of focus request. AUDIOFOCUS_GAIN_TRANSIENT is recommended so
1930     *    media applications resume after a call
1931     */
1932    public void requestAudioFocusForCall(int streamType, int durationHint) {
1933        IAudioService service = getService();
1934        try {
1935            service.requestAudioFocus(streamType, durationHint, mICallBack, null,
1936                    AudioService.IN_VOICE_COMM_FOCUS_ID,
1937                    "system" /* dump-friendly package name */);
1938        } catch (RemoteException e) {
1939            Log.e(TAG, "Can't call requestAudioFocusForCall() on AudioService due to "+e);
1940        }
1941    }
1942
1943    /**
1944     * @hide
1945     * Used internally by telephony package to abandon audio focus, typically after a call or
1946     * when ringing ends and the call is rejected or not answered.
1947     * Should match one or more calls to {@link #requestAudioFocusForCall(int, int)}.
1948     */
1949    public void abandonAudioFocusForCall() {
1950        IAudioService service = getService();
1951        try {
1952            service.abandonAudioFocus(null, AudioService.IN_VOICE_COMM_FOCUS_ID);
1953        } catch (RemoteException e) {
1954            Log.e(TAG, "Can't call abandonAudioFocusForCall() on AudioService due to "+e);
1955        }
1956    }
1957
1958    /**
1959     *  Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
1960     *  @param l the listener with which focus was requested.
1961     *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
1962     */
1963    public int abandonAudioFocus(OnAudioFocusChangeListener l) {
1964        int status = AUDIOFOCUS_REQUEST_FAILED;
1965        unregisterAudioFocusListener(l);
1966        IAudioService service = getService();
1967        try {
1968            status = service.abandonAudioFocus(mAudioFocusDispatcher,
1969                    getIdForAudioFocusListener(l));
1970        } catch (RemoteException e) {
1971            Log.e(TAG, "Can't call abandonAudioFocus() on AudioService due to "+e);
1972        }
1973        return status;
1974    }
1975
1976
1977    //====================================================================
1978    // Remote Control
1979    /**
1980     * Register a component to be the sole receiver of MEDIA_BUTTON intents.
1981     * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
1982     *      that will receive the media button intent. This broadcast receiver must be declared
1983     *      in the application manifest. The package of the component must match that of
1984     *      the context you're registering from.
1985     */
1986    public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
1987        if (eventReceiver == null) {
1988            return;
1989        }
1990        if (!eventReceiver.getPackageName().equals(mContext.getPackageName())) {
1991            Log.e(TAG, "registerMediaButtonEventReceiver() error: " +
1992                    "receiver and context package names don't match");
1993            return;
1994        }
1995        // construct a PendingIntent for the media button and register it
1996        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
1997        //     the associated intent will be handled by the component being registered
1998        mediaButtonIntent.setComponent(eventReceiver);
1999        PendingIntent pi = PendingIntent.getBroadcast(mContext,
2000                0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
2001        registerMediaButtonIntent(pi, eventReceiver);
2002    }
2003
2004    /**
2005     * @hide
2006     * no-op if (pi == null) or (eventReceiver == null)
2007     */
2008    public void registerMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {
2009        if ((pi == null) || (eventReceiver == null)) {
2010            Log.e(TAG, "Cannot call registerMediaButtonIntent() with a null parameter");
2011            return;
2012        }
2013        IAudioService service = getService();
2014        try {
2015            // pi != null
2016            service.registerMediaButtonIntent(pi, eventReceiver);
2017        } catch (RemoteException e) {
2018            Log.e(TAG, "Dead object in registerMediaButtonIntent"+e);
2019        }
2020    }
2021
2022    /**
2023     * @hide
2024     * Used internally by telephony package to register an intent receiver for ACTION_MEDIA_BUTTON.
2025     * @param eventReceiver the component that will receive the media button key events,
2026     *          no-op if eventReceiver is null
2027     */
2028    public void registerMediaButtonEventReceiverForCalls(ComponentName eventReceiver) {
2029        if (eventReceiver == null) {
2030            return;
2031        }
2032        IAudioService service = getService();
2033        try {
2034            // eventReceiver != null
2035            service.registerMediaButtonEventReceiverForCalls(eventReceiver);
2036        } catch (RemoteException e) {
2037            Log.e(TAG, "Dead object in registerMediaButtonEventReceiverForCalls", e);
2038        }
2039    }
2040
2041    /**
2042     * @hide
2043     */
2044    public void unregisterMediaButtonEventReceiverForCalls() {
2045        IAudioService service = getService();
2046        try {
2047            service.unregisterMediaButtonEventReceiverForCalls();
2048        } catch (RemoteException e) {
2049            Log.e(TAG, "Dead object in unregisterMediaButtonEventReceiverForCalls", e);
2050        }
2051    }
2052
2053    /**
2054     * Unregister the receiver of MEDIA_BUTTON intents.
2055     * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
2056     *      that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.
2057     */
2058    public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
2059        if (eventReceiver == null) {
2060            return;
2061        }
2062        // construct a PendingIntent for the media button and unregister it
2063        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2064        //     the associated intent will be handled by the component being registered
2065        mediaButtonIntent.setComponent(eventReceiver);
2066        PendingIntent pi = PendingIntent.getBroadcast(mContext,
2067                0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
2068        unregisterMediaButtonIntent(pi, eventReceiver);
2069    }
2070
2071    /**
2072     * @hide
2073     */
2074    public void unregisterMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {
2075        IAudioService service = getService();
2076        try {
2077            service.unregisterMediaButtonIntent(pi, eventReceiver);
2078        } catch (RemoteException e) {
2079            Log.e(TAG, "Dead object in unregisterMediaButtonIntent"+e);
2080        }
2081    }
2082
2083    /**
2084     * Registers the remote control client for providing information to display on the remote
2085     * controls.
2086     * @param rcClient The remote control client from which remote controls will receive
2087     *      information to display.
2088     * @see RemoteControlClient
2089     */
2090    public void registerRemoteControlClient(RemoteControlClient rcClient) {
2091        if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
2092            return;
2093        }
2094        IAudioService service = getService();
2095        try {
2096            service.registerRemoteControlClient(rcClient.getRcMediaIntent(),   /* mediaIntent   */
2097                    rcClient.getIRemoteControlClient(),                        /* rcClient      */
2098                    // used to match media button event receiver and audio focus
2099                    mContext.getPackageName());                                /* packageName   */
2100        } catch (RemoteException e) {
2101            Log.e(TAG, "Dead object in registerRemoteControlClient"+e);
2102        }
2103    }
2104
2105    /**
2106     * Unregisters the remote control client that was providing information to display on the
2107     * remote controls.
2108     * @param rcClient The remote control client to unregister.
2109     * @see #registerRemoteControlClient(RemoteControlClient)
2110     */
2111    public void unregisterRemoteControlClient(RemoteControlClient rcClient) {
2112        if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
2113            return;
2114        }
2115        IAudioService service = getService();
2116        try {
2117            service.unregisterRemoteControlClient(rcClient.getRcMediaIntent(), /* mediaIntent   */
2118                    rcClient.getIRemoteControlClient());                       /* rcClient      */
2119        } catch (RemoteException e) {
2120            Log.e(TAG, "Dead object in unregisterRemoteControlClient"+e);
2121        }
2122    }
2123
2124    /**
2125     * @hide
2126     * Registers a remote control display that will be sent information by remote control clients.
2127     * @param rcd
2128     */
2129    public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {
2130        if (rcd == null) {
2131            return;
2132        }
2133        IAudioService service = getService();
2134        try {
2135            service.registerRemoteControlDisplay(rcd);
2136        } catch (RemoteException e) {
2137            Log.e(TAG, "Dead object in registerRemoteControlDisplay " + e);
2138        }
2139    }
2140
2141    /**
2142     * @hide
2143     * Unregisters a remote control display that was sent information by remote control clients.
2144     * @param rcd
2145     */
2146    public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
2147        if (rcd == null) {
2148            return;
2149        }
2150        IAudioService service = getService();
2151        try {
2152            service.unregisterRemoteControlDisplay(rcd);
2153        } catch (RemoteException e) {
2154            Log.e(TAG, "Dead object in unregisterRemoteControlDisplay " + e);
2155        }
2156    }
2157
2158    /**
2159     * @hide
2160     * Sets the artwork size a remote control display expects when receiving bitmaps.
2161     * @param rcd
2162     * @param w the maximum width of the expected bitmap. Negative values indicate it is
2163     *   useless to send artwork.
2164     * @param h the maximum height of the expected bitmap. Negative values indicate it is
2165     *   useless to send artwork.
2166     */
2167    public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
2168        if (rcd == null) {
2169            return;
2170        }
2171        IAudioService service = getService();
2172        try {
2173            service.remoteControlDisplayUsesBitmapSize(rcd, w, h);
2174        } catch (RemoteException e) {
2175            Log.e(TAG, "Dead object in remoteControlDisplayUsesBitmapSize " + e);
2176        }
2177    }
2178
2179    // FIXME remove because we are not using intents anymore between AudioService and RcDisplay
2180    /**
2181     * @hide
2182     * Broadcast intent action indicating that the displays on the remote controls
2183     * should be updated because a new remote control client is now active. If there is no
2184     * {@link #EXTRA_REMOTE_CONTROL_CLIENT}, the remote control display should be cleared
2185     * because there is no valid client to supply it with information.
2186     *
2187     * @see #EXTRA_REMOTE_CONTROL_CLIENT
2188     */
2189    public static final String REMOTE_CONTROL_CLIENT_CHANGED =
2190            "android.media.REMOTE_CONTROL_CLIENT_CHANGED";
2191
2192    // FIXME remove because we are not using intents anymore between AudioService and RcDisplay
2193    /**
2194     * @hide
2195     * The IRemoteControlClientDispatcher monotonically increasing generation counter.
2196     *
2197     * @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
2198     */
2199    public static final String EXTRA_REMOTE_CONTROL_CLIENT_GENERATION =
2200            "android.media.EXTRA_REMOTE_CONTROL_CLIENT_GENERATION";
2201
2202    // FIXME remove because we are not using intents anymore between AudioService and RcDisplay
2203    /**
2204     * @hide
2205     * The name of the RemoteControlClient.
2206     * This String is passed as the client name when calling methods from the
2207     * IRemoteControlClientDispatcher interface.
2208     *
2209     * @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
2210     */
2211    public static final String EXTRA_REMOTE_CONTROL_CLIENT_NAME =
2212            "android.media.EXTRA_REMOTE_CONTROL_CLIENT_NAME";
2213
2214    // FIXME remove because we are not using intents anymore between AudioService and RcDisplay
2215    /**
2216     * @hide
2217     * The media button event receiver associated with the RemoteControlClient.
2218     * The {@link android.content.ComponentName} value of the event receiver can be retrieved with
2219     * {@link android.content.ComponentName#unflattenFromString(String)}
2220     *
2221     * @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
2222     */
2223    public static final String EXTRA_REMOTE_CONTROL_EVENT_RECEIVER =
2224            "android.media.EXTRA_REMOTE_CONTROL_EVENT_RECEIVER";
2225
2226    // FIXME remove because we are not using intents anymore between AudioService and RcDisplay
2227    /**
2228     * @hide
2229     * The flags describing what information has changed in the current remote control client.
2230     *
2231     * @see #REMOTE_CONTROL_CLIENT_CHANGED_ACTION
2232     */
2233    public static final String EXTRA_REMOTE_CONTROL_CLIENT_INFO_CHANGED =
2234            "android.media.EXTRA_REMOTE_CONTROL_CLIENT_INFO_CHANGED";
2235
2236    /**
2237     *  @hide
2238     *  Reload audio settings. This method is called by Settings backup
2239     *  agent when audio settings are restored and causes the AudioService
2240     *  to read and apply restored settings.
2241     */
2242    public void reloadAudioSettings() {
2243        IAudioService service = getService();
2244        try {
2245            service.reloadAudioSettings();
2246        } catch (RemoteException e) {
2247            Log.e(TAG, "Dead object in reloadAudioSettings"+e);
2248        }
2249    }
2250
2251     /**
2252      * {@hide}
2253      */
2254     private final IBinder mICallBack = new Binder();
2255
2256    /**
2257     * Checks whether the phone is in silent mode, with or without vibrate.
2258     *
2259     * @return true if phone is in silent mode, with or without vibrate.
2260     *
2261     * @see #getRingerMode()
2262     *
2263     * @hide pending API Council approval
2264     */
2265    public boolean isSilentMode() {
2266        int ringerMode = getRingerMode();
2267        boolean silentMode =
2268            (ringerMode == RINGER_MODE_SILENT) ||
2269            (ringerMode == RINGER_MODE_VIBRATE);
2270        return silentMode;
2271    }
2272
2273    // This section re-defines new output device constants from AudioSystem, because the AudioSystem
2274    // class is not used by other parts of the framework, which instead use definitions and methods
2275    // from AudioManager. AudioSystem is an internal class used by AudioManager and AudioService.
2276
2277    /** {@hide} The audio output device code for the small speaker at the front of the device used
2278     *  when placing calls.  Does not refer to an in-ear headphone without attached microphone,
2279     *  such as earbuds, earphones, or in-ear monitors (IEM). Those would be handled as a
2280     *  {@link #DEVICE_OUT_WIRED_HEADPHONE}.
2281     */
2282    public static final int DEVICE_OUT_EARPIECE = AudioSystem.DEVICE_OUT_EARPIECE;
2283    /** {@hide} The audio output device code for the built-in speaker */
2284    public static final int DEVICE_OUT_SPEAKER = AudioSystem.DEVICE_OUT_SPEAKER;
2285    /** {@hide} The audio output device code for a wired headset with attached microphone */
2286    public static final int DEVICE_OUT_WIRED_HEADSET = AudioSystem.DEVICE_OUT_WIRED_HEADSET;
2287    /** {@hide} The audio output device code for a wired headphone without attached microphone */
2288    public static final int DEVICE_OUT_WIRED_HEADPHONE = AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
2289    /** {@hide} The audio output device code for generic Bluetooth SCO, for voice */
2290    public static final int DEVICE_OUT_BLUETOOTH_SCO = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
2291    /** {@hide} The audio output device code for Bluetooth SCO Headset Profile (HSP) and
2292     *  Hands-Free Profile (HFP), for voice
2293     */
2294    public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET =
2295            AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2296    /** {@hide} The audio output device code for Bluetooth SCO car audio, for voice */
2297    public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT =
2298            AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2299    /** {@hide} The audio output device code for generic Bluetooth A2DP, for music */
2300    public static final int DEVICE_OUT_BLUETOOTH_A2DP = AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP;
2301    /** {@hide} The audio output device code for Bluetooth A2DP headphones, for music */
2302    public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES =
2303            AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2304    /** {@hide} The audio output device code for Bluetooth A2DP external speaker, for music */
2305    public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER =
2306            AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2307    /** {@hide} The audio output device code for S/PDIF or HDMI */
2308    public static final int DEVICE_OUT_AUX_DIGITAL = AudioSystem.DEVICE_OUT_AUX_DIGITAL;
2309    /** {@hide} The audio output device code for an analog wired headset attached via a
2310     *  docking station
2311     */
2312    public static final int DEVICE_OUT_ANLG_DOCK_HEADSET = AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
2313    /** {@hide} The audio output device code for a digital wired headset attached via a
2314     *  docking station
2315     */
2316    public static final int DEVICE_OUT_DGTL_DOCK_HEADSET = AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET;
2317    /** {@hide} The audio output device code for a USB audio accessory. The accessory is in USB host
2318     * mode and the Android device in USB device mode
2319     */
2320    public static final int DEVICE_OUT_USB_ACCESSORY = AudioSystem.DEVICE_OUT_USB_ACCESSORY;
2321    /** {@hide} The audio output device code for a USB audio device. The device is in USB device
2322     * mode and the Android device in USB host mode
2323     */
2324    public static final int DEVICE_OUT_USB_DEVICE = AudioSystem.DEVICE_OUT_USB_DEVICE;
2325    /** {@hide} This is not used as a returned value from {@link #getDevicesForStream}, but could be
2326     *  used in the future in a set method to select whatever default device is chosen by the
2327     *  platform-specific implementation.
2328     */
2329    public static final int DEVICE_OUT_DEFAULT = AudioSystem.DEVICE_OUT_DEFAULT;
2330
2331    /**
2332     * Return the enabled devices for the specified output stream type.
2333     *
2334     * @param streamType The stream type to query. One of
2335     *            {@link #STREAM_VOICE_CALL},
2336     *            {@link #STREAM_SYSTEM},
2337     *            {@link #STREAM_RING},
2338     *            {@link #STREAM_MUSIC},
2339     *            {@link #STREAM_ALARM},
2340     *            {@link #STREAM_NOTIFICATION},
2341     *            {@link #STREAM_DTMF}.
2342     *
2343     * @return The bit-mask "or" of audio output device codes for all enabled devices on this
2344     *         stream. Zero or more of
2345     *            {@link #DEVICE_OUT_EARPIECE},
2346     *            {@link #DEVICE_OUT_SPEAKER},
2347     *            {@link #DEVICE_OUT_WIRED_HEADSET},
2348     *            {@link #DEVICE_OUT_WIRED_HEADPHONE},
2349     *            {@link #DEVICE_OUT_BLUETOOTH_SCO},
2350     *            {@link #DEVICE_OUT_BLUETOOTH_SCO_HEADSET},
2351     *            {@link #DEVICE_OUT_BLUETOOTH_SCO_CARKIT},
2352     *            {@link #DEVICE_OUT_BLUETOOTH_A2DP},
2353     *            {@link #DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES},
2354     *            {@link #DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER},
2355     *            {@link #DEVICE_OUT_AUX_DIGITAL},
2356     *            {@link #DEVICE_OUT_ANLG_DOCK_HEADSET},
2357     *            {@link #DEVICE_OUT_DGTL_DOCK_HEADSET}.
2358     *            {@link #DEVICE_OUT_DEFAULT} is not used here.
2359     *
2360     * The implementation may support additional device codes beyond those listed, so
2361     * the application should ignore any bits which it does not recognize.
2362     * Note that the information may be imprecise when the implementation
2363     * cannot distinguish whether a particular device is enabled.
2364     *
2365     * {@hide}
2366     */
2367    public int getDevicesForStream(int streamType) {
2368        switch (streamType) {
2369        case STREAM_VOICE_CALL:
2370        case STREAM_SYSTEM:
2371        case STREAM_RING:
2372        case STREAM_MUSIC:
2373        case STREAM_ALARM:
2374        case STREAM_NOTIFICATION:
2375        case STREAM_DTMF:
2376            return AudioSystem.getDevicesForStream(streamType);
2377        default:
2378            return 0;
2379        }
2380    }
2381
2382    /** {@hide} */
2383    public IRingtonePlayer getRingtonePlayer() {
2384        try {
2385            return getService().getRingtonePlayer();
2386        } catch (RemoteException e) {
2387            return null;
2388        }
2389    }
2390}
2391