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