AudioManager.java revision 10804eb2818ab59b763a37b4f6151693c2ebba7b
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.Manifest;
20import android.annotation.NonNull;
21import android.annotation.SdkConstant;
22import android.annotation.SdkConstant.SdkConstantType;
23import android.annotation.SystemApi;
24import android.app.PendingIntent;
25import android.bluetooth.BluetoothDevice;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.media.RemoteController.OnClientUpdateListener;
30import android.media.audiopolicy.AudioPolicy;
31import android.media.audiopolicy.AudioPolicyConfig;
32import android.media.session.MediaController;
33import android.media.session.MediaSession;
34import android.media.session.MediaSessionLegacyHelper;
35import android.media.session.MediaSessionManager;
36import android.os.Binder;
37import android.os.Handler;
38import android.os.IBinder;
39import android.os.Looper;
40import android.os.Message;
41import android.os.Process;
42import android.os.RemoteException;
43import android.os.SystemClock;
44import android.os.ServiceManager;
45import android.provider.Settings;
46import android.util.Log;
47import android.view.KeyEvent;
48
49import java.util.ArrayList;
50import java.util.HashMap;
51import java.util.Iterator;
52
53/**
54 * AudioManager provides access to volume and ringer mode control.
55 * <p>
56 * Use <code>Context.getSystemService(Context.AUDIO_SERVICE)</code> to get
57 * an instance of this class.
58 */
59public class AudioManager {
60
61    private final Context mContext;
62    private long mVolumeKeyUpTime;
63    private final boolean mUseMasterVolume;
64    private final boolean mUseVolumeKeySounds;
65    private final boolean mUseFixedVolume;
66    private final Binder mToken = new Binder();
67    private static String TAG = "AudioManager";
68    private static final AudioPortEventHandler sAudioPortEventHandler = new AudioPortEventHandler();
69
70    /**
71     * Broadcast intent, a hint for applications that audio is about to become
72     * 'noisy' due to a change in audio outputs. For example, this intent may
73     * be sent when a wired headset is unplugged, or when an A2DP audio
74     * sink is disconnected, and the audio system is about to automatically
75     * switch audio route to the speaker. Applications that are controlling
76     * audio streams may consider pausing, reducing volume or some other action
77     * on receipt of this intent so as not to surprise the user with audio
78     * from the speaker.
79     */
80    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
81    public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY";
82
83    /**
84     * Sticky broadcast intent action indicating that the ringer mode has
85     * changed. Includes the new ringer mode.
86     *
87     * @see #EXTRA_RINGER_MODE
88     */
89    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
90    public static final String RINGER_MODE_CHANGED_ACTION = "android.media.RINGER_MODE_CHANGED";
91
92    /**
93     * @hide
94     * Sticky broadcast intent action indicating that the internal ringer mode has
95     * changed. Includes the new ringer mode.
96     *
97     * @see #EXTRA_RINGER_MODE
98     */
99    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
100    public static final String INTERNAL_RINGER_MODE_CHANGED_ACTION =
101            "android.media.INTERNAL_RINGER_MODE_CHANGED_ACTION";
102
103    /**
104     * The new ringer mode.
105     *
106     * @see #RINGER_MODE_CHANGED_ACTION
107     * @see #RINGER_MODE_NORMAL
108     * @see #RINGER_MODE_SILENT
109     * @see #RINGER_MODE_VIBRATE
110     */
111    public static final String EXTRA_RINGER_MODE = "android.media.EXTRA_RINGER_MODE";
112
113    /**
114     * Broadcast intent action indicating that the vibrate setting has
115     * changed. Includes the vibrate type and its new setting.
116     *
117     * @see #EXTRA_VIBRATE_TYPE
118     * @see #EXTRA_VIBRATE_SETTING
119     * @deprecated Applications should maintain their own vibrate policy based on
120     * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
121     */
122    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
123    public static final String VIBRATE_SETTING_CHANGED_ACTION =
124        "android.media.VIBRATE_SETTING_CHANGED";
125
126    /**
127     * @hide Broadcast intent when the volume for a particular stream type changes.
128     * Includes the stream, the new volume and previous volumes.
129     * Notes:
130     *  - for internal platform use only, do not make public,
131     *  - never used for "remote" volume changes
132     *
133     * @see #EXTRA_VOLUME_STREAM_TYPE
134     * @see #EXTRA_VOLUME_STREAM_VALUE
135     * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
136     */
137    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
138    public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";
139
140    /**
141     * @hide Broadcast intent when a stream mute state changes.
142     * Includes the stream that changed and the new mute state
143     *
144     * @see #EXTRA_VOLUME_STREAM_TYPE
145     * @see #EXTRA_STREAM_VOLUME_MUTED
146     */
147    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
148    public static final String STREAM_MUTE_CHANGED_ACTION =
149        "android.media.STREAM_MUTE_CHANGED_ACTION";
150
151    /**
152     * @hide Broadcast intent when the master volume changes.
153     * Includes the new volume
154     *
155     * @see #EXTRA_MASTER_VOLUME_VALUE
156     * @see #EXTRA_PREV_MASTER_VOLUME_VALUE
157     */
158    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
159    public static final String MASTER_VOLUME_CHANGED_ACTION =
160        "android.media.MASTER_VOLUME_CHANGED_ACTION";
161
162    /**
163     * @hide Broadcast intent when the master mute state changes.
164     * Includes the the new volume
165     *
166     * @see #EXTRA_MASTER_VOLUME_MUTED
167     */
168    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
169    public static final String MASTER_MUTE_CHANGED_ACTION =
170        "android.media.MASTER_MUTE_CHANGED_ACTION";
171
172    /**
173     * The new vibrate setting for a particular type.
174     *
175     * @see #VIBRATE_SETTING_CHANGED_ACTION
176     * @see #EXTRA_VIBRATE_TYPE
177     * @see #VIBRATE_SETTING_ON
178     * @see #VIBRATE_SETTING_OFF
179     * @see #VIBRATE_SETTING_ONLY_SILENT
180     * @deprecated Applications should maintain their own vibrate policy based on
181     * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
182     */
183    public static final String EXTRA_VIBRATE_SETTING = "android.media.EXTRA_VIBRATE_SETTING";
184
185    /**
186     * The vibrate type whose setting has changed.
187     *
188     * @see #VIBRATE_SETTING_CHANGED_ACTION
189     * @see #VIBRATE_TYPE_NOTIFICATION
190     * @see #VIBRATE_TYPE_RINGER
191     * @deprecated Applications should maintain their own vibrate policy based on
192     * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
193     */
194    public static final String EXTRA_VIBRATE_TYPE = "android.media.EXTRA_VIBRATE_TYPE";
195
196    /**
197     * @hide The stream type for the volume changed intent.
198     */
199    public static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE";
200
201    /**
202     * @hide The volume associated with the stream for the volume changed intent.
203     */
204    public static final String EXTRA_VOLUME_STREAM_VALUE =
205        "android.media.EXTRA_VOLUME_STREAM_VALUE";
206
207    /**
208     * @hide The previous volume associated with the stream for the volume changed intent.
209     */
210    public static final String EXTRA_PREV_VOLUME_STREAM_VALUE =
211        "android.media.EXTRA_PREV_VOLUME_STREAM_VALUE";
212
213    /**
214     * @hide The new master volume value for the master volume changed intent.
215     * Value is integer between 0 and 100 inclusive.
216     */
217    public static final String EXTRA_MASTER_VOLUME_VALUE =
218        "android.media.EXTRA_MASTER_VOLUME_VALUE";
219
220    /**
221     * @hide The previous master volume value for the master volume changed intent.
222     * Value is integer between 0 and 100 inclusive.
223     */
224    public static final String EXTRA_PREV_MASTER_VOLUME_VALUE =
225        "android.media.EXTRA_PREV_MASTER_VOLUME_VALUE";
226
227    /**
228     * @hide The new master volume mute state for the master mute changed intent.
229     * Value is boolean
230     */
231    public static final String EXTRA_MASTER_VOLUME_MUTED =
232        "android.media.EXTRA_MASTER_VOLUME_MUTED";
233
234    /**
235     * @hide The new stream volume mute state for the stream mute changed intent.
236     * Value is boolean
237     */
238    public static final String EXTRA_STREAM_VOLUME_MUTED =
239        "android.media.EXTRA_STREAM_VOLUME_MUTED";
240
241    /**
242     * Broadcast Action: Wired Headset plugged in or unplugged.
243     *
244     * You <em>cannot</em> receive this through components declared
245     * in manifests, only by explicitly registering for it with
246     * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)
247     * Context.registerReceiver()}.
248     *
249     * <p>The intent will have the following extra values:
250     * <ul>
251     *   <li><em>state</em> - 0 for unplugged, 1 for plugged. </li>
252     *   <li><em>name</em> - Headset type, human readable string </li>
253     *   <li><em>microphone</em> - 1 if headset has a microphone, 0 otherwise </li>
254     * </ul>
255     * </ul>
256     */
257    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
258    public static final String ACTION_HEADSET_PLUG =
259            "android.intent.action.HEADSET_PLUG";
260
261    /**
262     * Broadcast Action: A sticky broadcast indicating an HMDI cable was plugged or unplugged
263     *
264     * The intent will have the following extra values: {@link #EXTRA_AUDIO_PLUG_STATE},
265     * {@link #EXTRA_MAX_CHANNEL_COUNT}, {@link #EXTRA_ENCODINGS}.
266     * <p>It can only be received by explicitly registering for it with
267     * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)}.
268     */
269    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
270    public static final String ACTION_HDMI_AUDIO_PLUG =
271            "android.media.action.HDMI_AUDIO_PLUG";
272
273    /**
274     * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to communicate whether HDMI is plugged in
275     * or unplugged.
276     * An integer value of 1 indicates a plugged-in state, 0 is unplugged.
277     */
278    public static final String EXTRA_AUDIO_PLUG_STATE = "android.media.extra.AUDIO_PLUG_STATE";
279
280    /**
281     * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to define the maximum number of channels
282     * supported by the HDMI device.
283     * The corresponding integer value is only available when the device is plugged in (as expressed
284     * by {@link #EXTRA_AUDIO_PLUG_STATE}).
285     */
286    public static final String EXTRA_MAX_CHANNEL_COUNT = "android.media.extra.MAX_CHANNEL_COUNT";
287
288    /**
289     * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to define the audio encodings supported by
290     * the connected HDMI device.
291     * The corresponding array of encoding values is only available when the device is plugged in
292     * (as expressed by {@link #EXTRA_AUDIO_PLUG_STATE}). Encoding values are defined in
293     * {@link AudioFormat} (for instance see {@link AudioFormat#ENCODING_PCM_16BIT}). Use
294     * {@link android.content.Intent#getIntArrayExtra(String)} to retrieve the encoding values.
295     */
296    public static final String EXTRA_ENCODINGS = "android.media.extra.ENCODINGS";
297
298    /** The audio stream for phone calls */
299    public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
300    /** The audio stream for system sounds */
301    public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
302    /** The audio stream for the phone ring */
303    public static final int STREAM_RING = AudioSystem.STREAM_RING;
304    /** The audio stream for music playback */
305    public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
306    /** The audio stream for alarms */
307    public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
308    /** The audio stream for notifications */
309    public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
310    /** @hide The audio stream for phone calls when connected to bluetooth */
311    public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
312    /** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
313    public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
314    /** The audio stream for DTMF Tones */
315    public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
316    /** @hide The audio stream for text to speech (TTS) */
317    public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
318    /** Number of audio streams */
319    /**
320     * @deprecated Use AudioSystem.getNumStreamTypes() instead
321     */
322    @Deprecated public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
323
324    /**
325     * Increase the ringer volume.
326     *
327     * @see #adjustVolume(int, int)
328     * @see #adjustStreamVolume(int, int, int)
329     */
330    public static final int ADJUST_RAISE = 1;
331
332    /**
333     * Decrease the ringer volume.
334     *
335     * @see #adjustVolume(int, int)
336     * @see #adjustStreamVolume(int, int, int)
337     */
338    public static final int ADJUST_LOWER = -1;
339
340    /**
341     * Maintain the previous ringer volume. This may be useful when needing to
342     * show the volume toast without actually modifying the volume.
343     *
344     * @see #adjustVolume(int, int)
345     * @see #adjustStreamVolume(int, int, int)
346     */
347    public static final int ADJUST_SAME = 0;
348
349    /**
350     * Mute the volume. Has no effect if the stream is already muted.
351     *
352     * @see #adjustVolume(int, int)
353     * @see #adjustStreamVolume(int, int, int)
354     */
355    public static final int ADJUST_MUTE = -100;
356
357    /**
358     * Unmute the volume. Has no effect if the stream is not muted.
359     *
360     * @see #adjustVolume(int, int)
361     * @see #adjustStreamVolume(int, int, int)
362     */
363    public static final int ADJUST_UNMUTE = 100;
364
365    /**
366     * Toggle the mute state. If muted the stream will be unmuted. If not muted
367     * the stream will be muted.
368     *
369     * @see #adjustVolume(int, int)
370     * @see #adjustStreamVolume(int, int, int)
371     */
372    public static final int ADJUST_TOGGLE_MUTE = 101;
373
374    // Flags should be powers of 2!
375
376    /**
377     * Show a toast containing the current volume.
378     *
379     * @see #adjustStreamVolume(int, int, int)
380     * @see #adjustVolume(int, int)
381     * @see #setStreamVolume(int, int, int)
382     * @see #setRingerMode(int)
383     */
384    public static final int FLAG_SHOW_UI = 1 << 0;
385
386    /**
387     * Whether to include ringer modes as possible options when changing volume.
388     * For example, if true and volume level is 0 and the volume is adjusted
389     * with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent or
390     * vibrate mode.
391     * <p>
392     * By default this is on for the ring stream. If this flag is included,
393     * this behavior will be present regardless of the stream type being
394     * affected by the ringer mode.
395     *
396     * @see #adjustVolume(int, int)
397     * @see #adjustStreamVolume(int, int, int)
398     */
399    public static final int FLAG_ALLOW_RINGER_MODES = 1 << 1;
400
401    /**
402     * Whether to play a sound when changing the volume.
403     * <p>
404     * If this is given to {@link #adjustVolume(int, int)} or
405     * {@link #adjustSuggestedStreamVolume(int, int, int)}, it may be ignored
406     * in some cases (for example, the decided stream type is not
407     * {@link AudioManager#STREAM_RING}, or the volume is being adjusted
408     * downward).
409     *
410     * @see #adjustStreamVolume(int, int, int)
411     * @see #adjustVolume(int, int)
412     * @see #setStreamVolume(int, int, int)
413     */
414    public static final int FLAG_PLAY_SOUND = 1 << 2;
415
416    /**
417     * Removes any sounds/vibrate that may be in the queue, or are playing (related to
418     * changing volume).
419     */
420    public static final int FLAG_REMOVE_SOUND_AND_VIBRATE = 1 << 3;
421
422    /**
423     * Whether to vibrate if going into the vibrate ringer mode.
424     */
425    public static final int FLAG_VIBRATE = 1 << 4;
426
427    /**
428     * Indicates to VolumePanel that the volume slider should be disabled as user
429     * cannot change the stream volume
430     * @hide
431     */
432    public static final int FLAG_FIXED_VOLUME = 1 << 5;
433
434    /**
435     * Indicates the volume set/adjust call is for Bluetooth absolute volume
436     * @hide
437     */
438    public static final int FLAG_BLUETOOTH_ABS_VOLUME = 1 << 6;
439
440    /**
441     * Adjusting the volume was prevented due to silent mode, display a hint in the UI.
442     * @hide
443     */
444    public static final int FLAG_SHOW_SILENT_HINT = 1 << 7;
445
446    /**
447     * Indicates the volume call is for Hdmi Cec system audio volume
448     * @hide
449     */
450    public static final int FLAG_HDMI_SYSTEM_AUDIO_VOLUME = 1 << 8;
451
452    /**
453     * Indicates that this should only be handled if media is actively playing.
454     * @hide
455     */
456    public static final int FLAG_ACTIVE_MEDIA_ONLY = 1 << 9;
457
458    /**
459     * Like FLAG_SHOW_UI, but only dialog warnings and confirmations, no sliders.
460     * @hide
461     */
462    public static final int FLAG_SHOW_UI_WARNINGS = 1 << 10;
463
464    /**
465     * Adjusting the volume down from vibrated was prevented, display a hint in the UI.
466     * @hide
467     */
468    public static final int FLAG_SHOW_VIBRATE_HINT = 1 << 11;
469
470    private static final String[] FLAG_NAMES = {
471        "FLAG_SHOW_UI",
472        "FLAG_ALLOW_RINGER_MODES",
473        "FLAG_PLAY_SOUND",
474        "FLAG_REMOVE_SOUND_AND_VIBRATE",
475        "FLAG_VIBRATE",
476        "FLAG_FIXED_VOLUME",
477        "FLAG_BLUETOOTH_ABS_VOLUME",
478        "FLAG_SHOW_SILENT_HINT",
479        "FLAG_HDMI_SYSTEM_AUDIO_VOLUME",
480        "FLAG_ACTIVE_MEDIA_ONLY",
481        "FLAG_SHOW_UI_WARNINGS",
482        "FLAG_SHOW_VIBRATE_HINT",
483    };
484
485    /** @hide */
486    public static String flagsToString(int flags) {
487        final StringBuilder sb = new StringBuilder();
488        for (int i = 0; i < FLAG_NAMES.length; i++) {
489            final int flag = 1 << i;
490            if ((flags & flag) != 0) {
491                if (sb.length() > 0) {
492                    sb.append(',');
493                }
494                sb.append(FLAG_NAMES[i]);
495                flags &= ~flag;
496            }
497        }
498        if (flags != 0) {
499            if (sb.length() > 0) {
500                sb.append(',');
501            }
502            sb.append(flags);
503        }
504        return sb.toString();
505    }
506
507    /**
508     * Ringer mode that will be silent and will not vibrate. (This overrides the
509     * vibrate setting.)
510     *
511     * @see #setRingerMode(int)
512     * @see #getRingerMode()
513     */
514    public static final int RINGER_MODE_SILENT = 0;
515
516    /**
517     * Ringer mode that will be silent and will vibrate. (This will cause the
518     * phone ringer to always vibrate, but the notification vibrate to only
519     * vibrate if set.)
520     *
521     * @see #setRingerMode(int)
522     * @see #getRingerMode()
523     */
524    public static final int RINGER_MODE_VIBRATE = 1;
525
526    /**
527     * Ringer mode that may be audible and may vibrate. It will be audible if
528     * the volume before changing out of this mode was audible. It will vibrate
529     * if the vibrate setting is on.
530     *
531     * @see #setRingerMode(int)
532     * @see #getRingerMode()
533     */
534    public static final int RINGER_MODE_NORMAL = 2;
535
536    /**
537     * Maximum valid ringer mode value. Values must start from 0 and be contiguous.
538     * @hide
539     */
540    public static final int RINGER_MODE_MAX = RINGER_MODE_NORMAL;
541
542    /**
543     * Vibrate type that corresponds to the ringer.
544     *
545     * @see #setVibrateSetting(int, int)
546     * @see #getVibrateSetting(int)
547     * @see #shouldVibrate(int)
548     * @deprecated Applications should maintain their own vibrate policy based on
549     * current ringer mode that can be queried via {@link #getRingerMode()}.
550     */
551    public static final int VIBRATE_TYPE_RINGER = 0;
552
553    /**
554     * Vibrate type that corresponds to notifications.
555     *
556     * @see #setVibrateSetting(int, int)
557     * @see #getVibrateSetting(int)
558     * @see #shouldVibrate(int)
559     * @deprecated Applications should maintain their own vibrate policy based on
560     * current ringer mode that can be queried via {@link #getRingerMode()}.
561     */
562    public static final int VIBRATE_TYPE_NOTIFICATION = 1;
563
564    /**
565     * Vibrate setting that suggests to never vibrate.
566     *
567     * @see #setVibrateSetting(int, int)
568     * @see #getVibrateSetting(int)
569     * @deprecated Applications should maintain their own vibrate policy based on
570     * current ringer mode that can be queried via {@link #getRingerMode()}.
571     */
572    public static final int VIBRATE_SETTING_OFF = 0;
573
574    /**
575     * Vibrate setting that suggests to vibrate when possible.
576     *
577     * @see #setVibrateSetting(int, int)
578     * @see #getVibrateSetting(int)
579     * @deprecated Applications should maintain their own vibrate policy based on
580     * current ringer mode that can be queried via {@link #getRingerMode()}.
581     */
582    public static final int VIBRATE_SETTING_ON = 1;
583
584    /**
585     * Vibrate setting that suggests to only vibrate when in the vibrate ringer
586     * mode.
587     *
588     * @see #setVibrateSetting(int, int)
589     * @see #getVibrateSetting(int)
590     * @deprecated Applications should maintain their own vibrate policy based on
591     * current ringer mode that can be queried via {@link #getRingerMode()}.
592     */
593    public static final int VIBRATE_SETTING_ONLY_SILENT = 2;
594
595    /**
596     * Suggests using the default stream type. This may not be used in all
597     * places a stream type is needed.
598     */
599    public static final int USE_DEFAULT_STREAM_TYPE = Integer.MIN_VALUE;
600
601    private static IAudioService sService;
602
603    /**
604     * @hide
605     */
606    public AudioManager(Context context) {
607        mContext = context;
608        mUseMasterVolume = mContext.getResources().getBoolean(
609                com.android.internal.R.bool.config_useMasterVolume);
610        mUseVolumeKeySounds = mContext.getResources().getBoolean(
611                com.android.internal.R.bool.config_useVolumeKeySounds);
612        mUseFixedVolume = mContext.getResources().getBoolean(
613                com.android.internal.R.bool.config_useFixedVolume);
614        sAudioPortEventHandler.init();
615    }
616
617    private static IAudioService getService()
618    {
619        if (sService != null) {
620            return sService;
621        }
622        IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
623        sService = IAudioService.Stub.asInterface(b);
624        return sService;
625    }
626
627    /**
628     * Sends a simulated key event for a media button.
629     * To simulate a key press, you must first send a KeyEvent built with a
630     * {@link KeyEvent#ACTION_DOWN} action, then another event with the {@link KeyEvent#ACTION_UP}
631     * action.
632     * <p>The key event will be sent to the current media key event consumer which registered with
633     * {@link AudioManager#registerMediaButtonEventReceiver(PendingIntent)}.
634     * @param keyEvent a {@link KeyEvent} instance whose key code is one of
635     *     {@link KeyEvent#KEYCODE_MUTE},
636     *     {@link KeyEvent#KEYCODE_HEADSETHOOK},
637     *     {@link KeyEvent#KEYCODE_MEDIA_PLAY},
638     *     {@link KeyEvent#KEYCODE_MEDIA_PAUSE},
639     *     {@link KeyEvent#KEYCODE_MEDIA_PLAY_PAUSE},
640     *     {@link KeyEvent#KEYCODE_MEDIA_STOP},
641     *     {@link KeyEvent#KEYCODE_MEDIA_NEXT},
642     *     {@link KeyEvent#KEYCODE_MEDIA_PREVIOUS},
643     *     {@link KeyEvent#KEYCODE_MEDIA_REWIND},
644     *     {@link KeyEvent#KEYCODE_MEDIA_RECORD},
645     *     {@link KeyEvent#KEYCODE_MEDIA_FAST_FORWARD},
646     *     {@link KeyEvent#KEYCODE_MEDIA_CLOSE},
647     *     {@link KeyEvent#KEYCODE_MEDIA_EJECT},
648     *     or {@link KeyEvent#KEYCODE_MEDIA_AUDIO_TRACK}.
649     */
650    public void dispatchMediaKeyEvent(KeyEvent keyEvent) {
651        MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(mContext);
652        helper.sendMediaButtonEvent(keyEvent, false);
653    }
654
655    /**
656     * @hide
657     */
658    public void preDispatchKeyEvent(KeyEvent event, int stream) {
659        /*
660         * If the user hits another key within the play sound delay, then
661         * cancel the sound
662         */
663        int keyCode = event.getKeyCode();
664        if (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_UP
665                && keyCode != KeyEvent.KEYCODE_VOLUME_MUTE
666                && mVolumeKeyUpTime + AudioService.PLAY_SOUND_DELAY
667                        > SystemClock.uptimeMillis()) {
668            /*
669             * The user has hit another key during the delay (e.g., 300ms)
670             * since the last volume key up, so cancel any sounds.
671             */
672            if (mUseMasterVolume) {
673                adjustMasterVolume(ADJUST_SAME, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
674            } else {
675                adjustSuggestedStreamVolume(ADJUST_SAME,
676                        stream, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
677            }
678        }
679    }
680
681    /**
682     * @hide
683     */
684    public void handleKeyDown(KeyEvent event, int stream) {
685        int keyCode = event.getKeyCode();
686        switch (keyCode) {
687            case KeyEvent.KEYCODE_VOLUME_UP:
688            case KeyEvent.KEYCODE_VOLUME_DOWN:
689                /*
690                 * Adjust the volume in on key down since it is more
691                 * responsive to the user.
692                 */
693                int flags = FLAG_SHOW_UI | FLAG_VIBRATE;
694
695                if (mUseMasterVolume) {
696                    adjustMasterVolume(
697                            keyCode == KeyEvent.KEYCODE_VOLUME_UP
698                                    ? ADJUST_RAISE
699                                    : ADJUST_LOWER,
700                            flags);
701                } else {
702                    adjustSuggestedStreamVolume(
703                            keyCode == KeyEvent.KEYCODE_VOLUME_UP
704                                    ? ADJUST_RAISE
705                                    : ADJUST_LOWER,
706                            stream,
707                            flags);
708                }
709                break;
710            case KeyEvent.KEYCODE_VOLUME_MUTE:
711                if (event.getRepeatCount() == 0) {
712                    MediaSessionLegacyHelper.getHelper(mContext).sendVolumeKeyEvent(event, false);
713                }
714                break;
715        }
716    }
717
718    /**
719     * @hide
720     */
721    public void handleKeyUp(KeyEvent event, int stream) {
722        int keyCode = event.getKeyCode();
723        switch (keyCode) {
724            case KeyEvent.KEYCODE_VOLUME_UP:
725            case KeyEvent.KEYCODE_VOLUME_DOWN:
726                /*
727                 * Play a sound. This is done on key up since we don't want the
728                 * sound to play when a user holds down volume down to mute.
729                 */
730                if (mUseVolumeKeySounds) {
731                    if (mUseMasterVolume) {
732                        adjustMasterVolume(ADJUST_SAME, FLAG_PLAY_SOUND);
733                    } else {
734                        int flags = FLAG_PLAY_SOUND;
735                        adjustSuggestedStreamVolume(
736                                ADJUST_SAME,
737                                stream,
738                                flags);
739                    }
740                }
741                mVolumeKeyUpTime = SystemClock.uptimeMillis();
742                break;
743            case KeyEvent.KEYCODE_VOLUME_MUTE:
744                MediaSessionLegacyHelper.getHelper(mContext).sendVolumeKeyEvent(event, false);
745                break;
746        }
747    }
748
749    /**
750     * Indicates if the device implements a fixed volume policy.
751     * <p>Some devices may not have volume control and may operate at a fixed volume,
752     * and may not enable muting or changing the volume of audio streams.
753     * This method will return true on such devices.
754     * <p>The following APIs have no effect when volume is fixed:
755     * <ul>
756     *   <li> {@link #adjustVolume(int, int)}
757     *   <li> {@link #adjustSuggestedStreamVolume(int, int, int)}
758     *   <li> {@link #adjustStreamVolume(int, int, int)}
759     *   <li> {@link #setStreamVolume(int, int, int)}
760     *   <li> {@link #setRingerMode(int)}
761     *   <li> {@link #setStreamSolo(int, boolean)}
762     *   <li> {@link #setStreamMute(int, boolean)}
763     * </ul>
764     */
765    public boolean isVolumeFixed() {
766        return mUseFixedVolume;
767    }
768
769    /**
770     * Adjusts the volume of a particular stream by one step in a direction.
771     * <p>
772     * This method should only be used by applications that replace the platform-wide
773     * management of audio settings or the main telephony application.
774     *
775     * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL},
776     * {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC} or
777     * {@link #STREAM_ALARM}
778     * @param direction The direction to adjust the volume. One of
779     *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
780     *            {@link #ADJUST_SAME}.
781     * @param flags One or more flags.
782     * @see #adjustVolume(int, int)
783     * @see #setStreamVolume(int, int, int)
784     */
785    public void adjustStreamVolume(int streamType, int direction, int flags) {
786        IAudioService service = getService();
787        try {
788            if (mUseMasterVolume) {
789                service.adjustMasterVolume(direction, flags, mContext.getOpPackageName());
790            } else {
791                service.adjustStreamVolume(streamType, direction, flags,
792                        mContext.getOpPackageName());
793            }
794        } catch (RemoteException e) {
795            Log.e(TAG, "Dead object in adjustStreamVolume", e);
796        }
797    }
798
799    /**
800     * Adjusts the volume of the most relevant stream. For example, if a call is
801     * active, it will have the highest priority regardless of if the in-call
802     * screen is showing. Another example, if music is playing in the background
803     * and a call is not active, the music stream will be adjusted.
804     * <p>
805     * This method should only be used by applications that replace the
806     * platform-wide management of audio settings or the main telephony
807     * application.
808     * <p>
809     * This method has no effect if the device implements a fixed volume policy
810     * as indicated by {@link #isVolumeFixed()}.
811     *
812     * @param direction The direction to adjust the volume. One of
813     *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE},
814     *            {@link #ADJUST_SAME}, {@link #ADJUST_MUTE},
815     *            {@link #ADJUST_UNMUTE}, or {@link #ADJUST_TOGGLE_MUTE}.
816     * @param flags One or more flags.
817     * @see #adjustSuggestedStreamVolume(int, int, int)
818     * @see #adjustStreamVolume(int, int, int)
819     * @see #setStreamVolume(int, int, int)
820     * @see #isVolumeFixed()
821     */
822    public void adjustVolume(int direction, int flags) {
823        IAudioService service = getService();
824        try {
825            if (mUseMasterVolume) {
826                service.adjustMasterVolume(direction, flags, mContext.getOpPackageName());
827            } else {
828                MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(mContext);
829                helper.sendAdjustVolumeBy(USE_DEFAULT_STREAM_TYPE, direction, flags);
830            }
831        } catch (RemoteException e) {
832            Log.e(TAG, "Dead object in adjustVolume", e);
833        }
834    }
835
836    /**
837     * Adjusts the volume of the most relevant stream, or the given fallback
838     * stream.
839     * <p>
840     * This method should only be used by applications that replace the
841     * platform-wide management of audio settings or the main telephony
842     * application.
843     * <p>
844     * This method has no effect if the device implements a fixed volume policy
845     * as indicated by {@link #isVolumeFixed()}.
846     *
847     * @param direction The direction to adjust the volume. One of
848     *            {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE},
849     *            {@link #ADJUST_SAME}, {@link #ADJUST_MUTE},
850     *            {@link #ADJUST_UNMUTE}, or {@link #ADJUST_TOGGLE_MUTE}.
851     * @param suggestedStreamType The stream type that will be used if there
852     *            isn't a relevant stream. {@link #USE_DEFAULT_STREAM_TYPE} is
853     *            valid here.
854     * @param flags One or more flags.
855     * @see #adjustVolume(int, int)
856     * @see #adjustStreamVolume(int, int, int)
857     * @see #setStreamVolume(int, int, int)
858     * @see #isVolumeFixed()
859     */
860    public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
861        IAudioService service = getService();
862        try {
863            if (mUseMasterVolume) {
864                service.adjustMasterVolume(direction, flags, mContext.getOpPackageName());
865            } else {
866                MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(mContext);
867                helper.sendAdjustVolumeBy(suggestedStreamType, direction, flags);
868            }
869        } catch (RemoteException e) {
870            Log.e(TAG, "Dead object in adjustSuggestedStreamVolume", e);
871        }
872    }
873
874    /**
875     * Adjusts the master volume for the device's audio amplifier.
876     * <p>
877     *
878     * @param steps The number of volume steps to adjust. A positive
879     *            value will raise the volume.
880     * @param flags One or more flags.
881     * @hide
882     */
883    public void adjustMasterVolume(int steps, int flags) {
884        IAudioService service = getService();
885        try {
886            service.adjustMasterVolume(steps, flags, mContext.getOpPackageName());
887        } catch (RemoteException e) {
888            Log.e(TAG, "Dead object in adjustMasterVolume", e);
889        }
890    }
891
892    /**
893     * Returns the current ringtone mode.
894     *
895     * @return The current ringtone mode, one of {@link #RINGER_MODE_NORMAL},
896     *         {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
897     * @see #setRingerMode(int)
898     */
899    public int getRingerMode() {
900        IAudioService service = getService();
901        try {
902            return service.getRingerModeExternal();
903        } catch (RemoteException e) {
904            Log.e(TAG, "Dead object in getRingerMode", e);
905            return RINGER_MODE_NORMAL;
906        }
907    }
908
909    /**
910     * Checks valid ringer mode values.
911     *
912     * @return true if the ringer mode indicated is valid, false otherwise.
913     *
914     * @see #setRingerMode(int)
915     * @hide
916     */
917    public static boolean isValidRingerMode(int ringerMode) {
918        if (ringerMode < 0 || ringerMode > RINGER_MODE_MAX) {
919            return false;
920        }
921        IAudioService service = getService();
922        try {
923            return service.isValidRingerMode(ringerMode);
924        } catch (RemoteException e) {
925            Log.e(TAG, "Dead object in isValidRingerMode", e);
926            return false;
927        }
928    }
929
930    /**
931     * Returns the maximum volume index for a particular stream.
932     *
933     * @param streamType The stream type whose maximum volume index is returned.
934     * @return The maximum valid volume index for the stream.
935     * @see #getStreamVolume(int)
936     */
937    public int getStreamMaxVolume(int streamType) {
938        IAudioService service = getService();
939        try {
940            if (mUseMasterVolume) {
941                return service.getMasterMaxVolume();
942            } else {
943                return service.getStreamMaxVolume(streamType);
944            }
945        } catch (RemoteException e) {
946            Log.e(TAG, "Dead object in getStreamMaxVolume", e);
947            return 0;
948        }
949    }
950
951    /**
952     * Returns the current volume index for a particular stream.
953     *
954     * @param streamType The stream type whose volume index is returned.
955     * @return The current volume index for the stream.
956     * @see #getStreamMaxVolume(int)
957     * @see #setStreamVolume(int, int, int)
958     */
959    public int getStreamVolume(int streamType) {
960        IAudioService service = getService();
961        try {
962            if (mUseMasterVolume) {
963                return service.getMasterVolume();
964            } else {
965                return service.getStreamVolume(streamType);
966            }
967        } catch (RemoteException e) {
968            Log.e(TAG, "Dead object in getStreamVolume", e);
969            return 0;
970        }
971    }
972
973    /**
974     * Get last audible volume before stream was muted.
975     *
976     * @hide
977     */
978    public int getLastAudibleStreamVolume(int streamType) {
979        IAudioService service = getService();
980        try {
981            if (mUseMasterVolume) {
982                return service.getLastAudibleMasterVolume();
983            } else {
984                return service.getLastAudibleStreamVolume(streamType);
985            }
986        } catch (RemoteException e) {
987            Log.e(TAG, "Dead object in getLastAudibleStreamVolume", e);
988            return 0;
989        }
990    }
991
992    /**
993     * Get the stream type whose volume is driving the UI sounds volume.
994     * UI sounds are screen lock/unlock, camera shutter, key clicks...
995     * It is assumed that this stream type is also tied to ringer mode changes.
996     * @hide
997     */
998    public int getMasterStreamType() {
999        IAudioService service = getService();
1000        try {
1001            return service.getMasterStreamType();
1002        } catch (RemoteException e) {
1003            Log.e(TAG, "Dead object in getMasterStreamType", e);
1004            return STREAM_RING;
1005        }
1006    }
1007
1008    /**
1009     * Sets the ringer mode.
1010     * <p>
1011     * Silent mode will mute the volume and will not vibrate. Vibrate mode will
1012     * mute the volume and vibrate. Normal mode will be audible and may vibrate
1013     * according to user settings.
1014     * <p>This method has no effect if the device implements a fixed volume policy
1015     * as indicated by {@link #isVolumeFixed()}.
1016     * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},
1017     *            {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
1018     * @see #getRingerMode()
1019     * @see #isVolumeFixed()
1020     */
1021    public void setRingerMode(int ringerMode) {
1022        if (!isValidRingerMode(ringerMode)) {
1023            return;
1024        }
1025        IAudioService service = getService();
1026        try {
1027            service.setRingerModeExternal(ringerMode, mContext.getOpPackageName());
1028        } catch (RemoteException e) {
1029            Log.e(TAG, "Dead object in setRingerMode", e);
1030        }
1031    }
1032
1033    /**
1034     * Sets the volume index for a particular stream.
1035     * <p>This method has no effect if the device implements a fixed volume policy
1036     * as indicated by {@link #isVolumeFixed()}.
1037     * @param streamType The stream whose volume index should be set.
1038     * @param index The volume index to set. See
1039     *            {@link #getStreamMaxVolume(int)} for the largest valid value.
1040     * @param flags One or more flags.
1041     * @see #getStreamMaxVolume(int)
1042     * @see #getStreamVolume(int)
1043     * @see #isVolumeFixed()
1044     */
1045    public void setStreamVolume(int streamType, int index, int flags) {
1046        IAudioService service = getService();
1047        try {
1048            if (mUseMasterVolume) {
1049                service.setMasterVolume(index, flags, mContext.getOpPackageName());
1050            } else {
1051                service.setStreamVolume(streamType, index, flags, mContext.getOpPackageName());
1052            }
1053        } catch (RemoteException e) {
1054            Log.e(TAG, "Dead object in setStreamVolume", e);
1055        }
1056    }
1057
1058    /**
1059     * Returns the maximum volume index for master volume.
1060     *
1061     * @hide
1062     */
1063    public int getMasterMaxVolume() {
1064        IAudioService service = getService();
1065        try {
1066            return service.getMasterMaxVolume();
1067        } catch (RemoteException e) {
1068            Log.e(TAG, "Dead object in getMasterMaxVolume", e);
1069            return 0;
1070        }
1071    }
1072
1073    /**
1074     * Returns the current volume index for master volume.
1075     *
1076     * @return The current volume index for master volume.
1077     * @hide
1078     */
1079    public int getMasterVolume() {
1080        IAudioService service = getService();
1081        try {
1082            return service.getMasterVolume();
1083        } catch (RemoteException e) {
1084            Log.e(TAG, "Dead object in getMasterVolume", e);
1085            return 0;
1086        }
1087    }
1088
1089    /**
1090     * Get last audible volume before master volume was muted.
1091     *
1092     * @hide
1093     */
1094    public int getLastAudibleMasterVolume() {
1095        IAudioService service = getService();
1096        try {
1097            return service.getLastAudibleMasterVolume();
1098        } catch (RemoteException e) {
1099            Log.e(TAG, "Dead object in getLastAudibleMasterVolume", e);
1100            return 0;
1101        }
1102    }
1103
1104    /**
1105     * Sets the volume index for master volume.
1106     *
1107     * @param index The volume index to set. See
1108     *            {@link #getMasterMaxVolume()} for the largest valid value.
1109     * @param flags One or more flags.
1110     * @see #getMasterMaxVolume()
1111     * @see #getMasterVolume()
1112     * @hide
1113     */
1114    public void setMasterVolume(int index, int flags) {
1115        IAudioService service = getService();
1116        try {
1117            service.setMasterVolume(index, flags, mContext.getOpPackageName());
1118        } catch (RemoteException e) {
1119            Log.e(TAG, "Dead object in setMasterVolume", e);
1120        }
1121    }
1122
1123    /**
1124     * Solo or unsolo a particular stream.
1125     * <p>
1126     * Do not use. This method has been deprecated and is now a no-op.
1127     * {@link #requestAudioFocus} should be used for exclusive audio playback.
1128     *
1129     * @param streamType The stream to be soloed/unsoloed.
1130     * @param state The required solo state: true for solo ON, false for solo
1131     *            OFF
1132     * @see #isVolumeFixed()
1133     * @deprecated Do not use. If you need exclusive audio playback use
1134     *             {@link #requestAudioFocus}.
1135     */
1136    @Deprecated
1137    public void setStreamSolo(int streamType, boolean state) {
1138        Log.w(TAG, "setStreamSolo has been deprecated. Do not use.");
1139    }
1140
1141    /**
1142     * Mute or unmute an audio stream.
1143     * <p>
1144     * This method should only be used by applications that replace the
1145     * platform-wide management of audio settings or the main telephony
1146     * application.
1147     * <p>
1148     * This method has no effect if the device implements a fixed volume policy
1149     * as indicated by {@link #isVolumeFixed()}.
1150     * <p>
1151     * This method was deprecated in API level 22. Prior to API level 22 this
1152     * method had significantly different behavior and should be used carefully.
1153     * The following applies only to pre-22 platforms:
1154     * <ul>
1155     * <li>The mute command is protected against client process death: if a
1156     * process with an active mute request on a stream dies, this stream will be
1157     * unmuted automatically.</li>
1158     * <li>The mute requests for a given stream are cumulative: the AudioManager
1159     * can receive several mute requests from one or more clients and the stream
1160     * will be unmuted only when the same number of unmute requests are
1161     * received.</li>
1162     * <li>For a better user experience, applications MUST unmute a muted stream
1163     * in onPause() and mute is again in onResume() if appropriate.</li>
1164     * </ul>
1165     *
1166     * @param streamType The stream to be muted/unmuted.
1167     * @param state The required mute state: true for mute ON, false for mute
1168     *            OFF
1169     * @see #isVolumeFixed()
1170     * @deprecated Use {@link #adjustStreamVolume(int, int, int)} with
1171     *             {@link #ADJUST_MUTE} or {@link #ADJUST_UNMUTE} instead.
1172     */
1173    @Deprecated
1174    public void setStreamMute(int streamType, boolean state) {
1175        Log.w(TAG, "setStreamMute is deprecated. adjustStreamVolume should be used instead.");
1176        int direction = state ? ADJUST_MUTE : ADJUST_UNMUTE;
1177        if (streamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1178            adjustSuggestedStreamVolume(direction, streamType, 0);
1179        } else {
1180            adjustStreamVolume(streamType, direction, 0);
1181        }
1182    }
1183
1184    /**
1185     * Returns the current mute state for a particular stream.
1186     *
1187     * @param streamType The stream to get mute state for.
1188     * @return The mute state for the given stream.
1189     * @see #adjustStreamVolume(int, int, int)
1190     */
1191    public boolean isStreamMute(int streamType) {
1192        IAudioService service = getService();
1193        try {
1194            return service.isStreamMute(streamType);
1195        } catch (RemoteException e) {
1196            Log.e(TAG, "Dead object in isStreamMute", e);
1197            return false;
1198        }
1199    }
1200
1201    /**
1202     * get master mute state.
1203     *
1204     * @hide
1205     */
1206    public boolean isMasterMute() {
1207        IAudioService service = getService();
1208        try {
1209            return service.isMasterMute();
1210        } catch (RemoteException e) {
1211            Log.e(TAG, "Dead object in isMasterMute", e);
1212            return false;
1213        }
1214    }
1215
1216    /**
1217     * forces the stream controlled by hard volume keys
1218     * specifying streamType == -1 releases control to the
1219     * logic.
1220     *
1221     * @hide
1222     */
1223    public void forceVolumeControlStream(int streamType) {
1224        if (mUseMasterVolume) {
1225            return;
1226        }
1227        IAudioService service = getService();
1228        try {
1229            service.forceVolumeControlStream(streamType, mICallBack);
1230        } catch (RemoteException e) {
1231            Log.e(TAG, "Dead object in forceVolumeControlStream", e);
1232        }
1233    }
1234
1235    /**
1236     * Returns whether a particular type should vibrate according to user
1237     * settings and the current ringer mode.
1238     * <p>
1239     * This shouldn't be needed by most clients that use notifications to
1240     * vibrate. The notification manager will not vibrate if the policy doesn't
1241     * allow it, so the client should always set a vibrate pattern and let the
1242     * notification manager control whether or not to actually vibrate.
1243     *
1244     * @param vibrateType The type of vibrate. One of
1245     *            {@link #VIBRATE_TYPE_NOTIFICATION} or
1246     *            {@link #VIBRATE_TYPE_RINGER}.
1247     * @return Whether the type should vibrate at the instant this method is
1248     *         called.
1249     * @see #setVibrateSetting(int, int)
1250     * @see #getVibrateSetting(int)
1251     * @deprecated Applications should maintain their own vibrate policy based on
1252     * current ringer mode that can be queried via {@link #getRingerMode()}.
1253     */
1254    public boolean shouldVibrate(int vibrateType) {
1255        IAudioService service = getService();
1256        try {
1257            return service.shouldVibrate(vibrateType);
1258        } catch (RemoteException e) {
1259            Log.e(TAG, "Dead object in shouldVibrate", e);
1260            return false;
1261        }
1262    }
1263
1264    /**
1265     * Returns whether the user's vibrate setting for a vibrate type.
1266     * <p>
1267     * This shouldn't be needed by most clients that want to vibrate, instead
1268     * see {@link #shouldVibrate(int)}.
1269     *
1270     * @param vibrateType The type of vibrate. One of
1271     *            {@link #VIBRATE_TYPE_NOTIFICATION} or
1272     *            {@link #VIBRATE_TYPE_RINGER}.
1273     * @return The vibrate setting, one of {@link #VIBRATE_SETTING_ON},
1274     *         {@link #VIBRATE_SETTING_OFF}, or
1275     *         {@link #VIBRATE_SETTING_ONLY_SILENT}.
1276     * @see #setVibrateSetting(int, int)
1277     * @see #shouldVibrate(int)
1278     * @deprecated Applications should maintain their own vibrate policy based on
1279     * current ringer mode that can be queried via {@link #getRingerMode()}.
1280     */
1281    public int getVibrateSetting(int vibrateType) {
1282        IAudioService service = getService();
1283        try {
1284            return service.getVibrateSetting(vibrateType);
1285        } catch (RemoteException e) {
1286            Log.e(TAG, "Dead object in getVibrateSetting", e);
1287            return VIBRATE_SETTING_OFF;
1288        }
1289    }
1290
1291    /**
1292     * Sets the setting for when the vibrate type should vibrate.
1293     * <p>
1294     * This method should only be used by applications that replace the platform-wide
1295     * management of audio settings or the main telephony application.
1296     *
1297     * @param vibrateType The type of vibrate. One of
1298     *            {@link #VIBRATE_TYPE_NOTIFICATION} or
1299     *            {@link #VIBRATE_TYPE_RINGER}.
1300     * @param vibrateSetting The vibrate setting, one of
1301     *            {@link #VIBRATE_SETTING_ON},
1302     *            {@link #VIBRATE_SETTING_OFF}, or
1303     *            {@link #VIBRATE_SETTING_ONLY_SILENT}.
1304     * @see #getVibrateSetting(int)
1305     * @see #shouldVibrate(int)
1306     * @deprecated Applications should maintain their own vibrate policy based on
1307     * current ringer mode that can be queried via {@link #getRingerMode()}.
1308     */
1309    public void setVibrateSetting(int vibrateType, int vibrateSetting) {
1310        IAudioService service = getService();
1311        try {
1312            service.setVibrateSetting(vibrateType, vibrateSetting);
1313        } catch (RemoteException e) {
1314            Log.e(TAG, "Dead object in setVibrateSetting", e);
1315        }
1316    }
1317
1318    /**
1319     * Sets the speakerphone on or off.
1320     * <p>
1321     * This method should only be used by applications that replace the platform-wide
1322     * management of audio settings or the main telephony application.
1323     *
1324     * @param on set <var>true</var> to turn on speakerphone;
1325     *           <var>false</var> to turn it off
1326     */
1327    public void setSpeakerphoneOn(boolean on){
1328        IAudioService service = getService();
1329        try {
1330            service.setSpeakerphoneOn(on);
1331        } catch (RemoteException e) {
1332            Log.e(TAG, "Dead object in setSpeakerphoneOn", e);
1333        }
1334    }
1335
1336    /**
1337     * Checks whether the speakerphone is on or off.
1338     *
1339     * @return true if speakerphone is on, false if it's off
1340     */
1341    public boolean isSpeakerphoneOn() {
1342        IAudioService service = getService();
1343        try {
1344            return service.isSpeakerphoneOn();
1345        } catch (RemoteException e) {
1346            Log.e(TAG, "Dead object in isSpeakerphoneOn", e);
1347            return false;
1348        }
1349     }
1350
1351    //====================================================================
1352    // Bluetooth SCO control
1353    /**
1354     * Sticky broadcast intent action indicating that the bluetoooth SCO audio
1355     * connection state has changed. The intent contains on extra {@link #EXTRA_SCO_AUDIO_STATE}
1356     * indicating the new state which is either {@link #SCO_AUDIO_STATE_DISCONNECTED}
1357     * or {@link #SCO_AUDIO_STATE_CONNECTED}
1358     *
1359     * @see #startBluetoothSco()
1360     * @deprecated Use  {@link #ACTION_SCO_AUDIO_STATE_UPDATED} instead
1361     */
1362    @Deprecated
1363    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1364    public static final String ACTION_SCO_AUDIO_STATE_CHANGED =
1365            "android.media.SCO_AUDIO_STATE_CHANGED";
1366
1367     /**
1368     * Sticky broadcast intent action indicating that the bluetoooth SCO audio
1369     * connection state has been updated.
1370     * <p>This intent has two extras:
1371     * <ul>
1372     *   <li> {@link #EXTRA_SCO_AUDIO_STATE} - The new SCO audio state. </li>
1373     *   <li> {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}- The previous SCO audio state. </li>
1374     * </ul>
1375     * <p> EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE can be any of:
1376     * <ul>
1377     *   <li> {@link #SCO_AUDIO_STATE_DISCONNECTED}, </li>
1378     *   <li> {@link #SCO_AUDIO_STATE_CONNECTING} or </li>
1379     *   <li> {@link #SCO_AUDIO_STATE_CONNECTED}, </li>
1380     * </ul>
1381     * @see #startBluetoothSco()
1382     */
1383    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1384    public static final String ACTION_SCO_AUDIO_STATE_UPDATED =
1385            "android.media.ACTION_SCO_AUDIO_STATE_UPDATED";
1386
1387    /**
1388     * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_CHANGED} or
1389     * {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the new bluetooth SCO connection state.
1390     */
1391    public static final String EXTRA_SCO_AUDIO_STATE =
1392            "android.media.extra.SCO_AUDIO_STATE";
1393
1394    /**
1395     * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the previous
1396     * bluetooth SCO connection state.
1397     */
1398    public static final String EXTRA_SCO_AUDIO_PREVIOUS_STATE =
1399            "android.media.extra.SCO_AUDIO_PREVIOUS_STATE";
1400
1401    /**
1402     * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
1403     * indicating that the SCO audio channel is not established
1404     */
1405    public static final int SCO_AUDIO_STATE_DISCONNECTED = 0;
1406    /**
1407     * Value for extra {@link #EXTRA_SCO_AUDIO_STATE} or {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}
1408     * indicating that the SCO audio channel is established
1409     */
1410    public static final int SCO_AUDIO_STATE_CONNECTED = 1;
1411    /**
1412     * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
1413     * indicating that the SCO audio channel is being established
1414     */
1415    public static final int SCO_AUDIO_STATE_CONNECTING = 2;
1416    /**
1417     * Value for extra EXTRA_SCO_AUDIO_STATE indicating that
1418     * there was an error trying to obtain the state
1419     */
1420    public static final int SCO_AUDIO_STATE_ERROR = -1;
1421
1422
1423    /**
1424     * Indicates if current platform supports use of SCO for off call use cases.
1425     * Application wanted to use bluetooth SCO audio when the phone is not in call
1426     * must first call this method to make sure that the platform supports this
1427     * feature.
1428     * @return true if bluetooth SCO can be used for audio when not in call
1429     *         false otherwise
1430     * @see #startBluetoothSco()
1431    */
1432    public boolean isBluetoothScoAvailableOffCall() {
1433        return mContext.getResources().getBoolean(
1434               com.android.internal.R.bool.config_bluetooth_sco_off_call);
1435    }
1436
1437    /**
1438     * Start bluetooth SCO audio connection.
1439     * <p>Requires Permission:
1440     *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1441     * <p>This method can be used by applications wanting to send and received audio
1442     * to/from a bluetooth SCO headset while the phone is not in call.
1443     * <p>As the SCO connection establishment can take several seconds,
1444     * applications should not rely on the connection to be available when the method
1445     * returns but instead register to receive the intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED}
1446     * and wait for the state to be {@link #SCO_AUDIO_STATE_CONNECTED}.
1447     * <p>As the ACTION_SCO_AUDIO_STATE_UPDATED intent is sticky, the application can check the SCO
1448     * audio state before calling startBluetoothSco() by reading the intent returned by the receiver
1449     * registration. If the state is already CONNECTED, no state change will be received via the
1450     * intent after calling startBluetoothSco(). It is however useful to call startBluetoothSco()
1451     * so that the connection stays active in case the current initiator stops the connection.
1452     * <p>Unless the connection is already active as described above, the state will always
1453     * transition from DISCONNECTED to CONNECTING and then either to CONNECTED if the connection
1454     * succeeds or back to DISCONNECTED if the connection fails (e.g no headset is connected).
1455     * <p>When finished with the SCO connection or if the establishment fails, the application must
1456     * call {@link #stopBluetoothSco()} to clear the request and turn down the bluetooth connection.
1457     * <p>Even if a SCO connection is established, the following restrictions apply on audio
1458     * output streams so that they can be routed to SCO headset:
1459     * <ul>
1460     *   <li> the stream type must be {@link #STREAM_VOICE_CALL} </li>
1461     *   <li> the format must be mono </li>
1462     *   <li> the sampling must be 16kHz or 8kHz </li>
1463     * </ul>
1464     * <p>The following restrictions apply on input streams:
1465     * <ul>
1466     *   <li> the format must be mono </li>
1467     *   <li> the sampling must be 8kHz </li>
1468     * </ul>
1469     * <p>Note that the phone application always has the priority on the usage of the SCO
1470     * connection for telephony. If this method is called while the phone is in call
1471     * it will be ignored. Similarly, if a call is received or sent while an application
1472     * is using the SCO connection, the connection will be lost for the application and NOT
1473     * returned automatically when the call ends.
1474     * <p>NOTE: up to and including API version
1475     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}, this method initiates a virtual
1476     * voice call to the bluetooth headset.
1477     * After API version {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} only a raw SCO audio
1478     * connection is established.
1479     * @see #stopBluetoothSco()
1480     * @see #ACTION_SCO_AUDIO_STATE_UPDATED
1481     */
1482    public void startBluetoothSco(){
1483        IAudioService service = getService();
1484        try {
1485            service.startBluetoothSco(mICallBack, mContext.getApplicationInfo().targetSdkVersion);
1486        } catch (RemoteException e) {
1487            Log.e(TAG, "Dead object in startBluetoothSco", e);
1488        }
1489    }
1490
1491    /**
1492     * @hide
1493     * Start bluetooth SCO audio connection in virtual call mode.
1494     * <p>Requires Permission:
1495     *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1496     * <p>Similar to {@link #startBluetoothSco()} with explicit selection of virtual call mode.
1497     * Telephony and communication applications (VoIP, Video Chat) should preferably select
1498     * virtual call mode.
1499     * Applications using voice input for search or commands should first try raw audio connection
1500     * with {@link #startBluetoothSco()} and fall back to startBluetoothScoVirtualCall() in case of
1501     * failure.
1502     * @see #startBluetoothSco()
1503     * @see #stopBluetoothSco()
1504     * @see #ACTION_SCO_AUDIO_STATE_UPDATED
1505     */
1506    public void startBluetoothScoVirtualCall() {
1507        IAudioService service = getService();
1508        try {
1509            service.startBluetoothScoVirtualCall(mICallBack);
1510        } catch (RemoteException e) {
1511            Log.e(TAG, "Dead object in startBluetoothScoVirtualCall", e);
1512        }
1513    }
1514
1515    /**
1516     * Stop bluetooth SCO audio connection.
1517     * <p>Requires Permission:
1518     *   {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1519     * <p>This method must be called by applications having requested the use of
1520     * bluetooth SCO audio with {@link #startBluetoothSco()} when finished with the SCO
1521     * connection or if connection fails.
1522     * @see #startBluetoothSco()
1523     */
1524    // Also used for connections started with {@link #startBluetoothScoVirtualCall()}
1525    public void stopBluetoothSco(){
1526        IAudioService service = getService();
1527        try {
1528            service.stopBluetoothSco(mICallBack);
1529        } catch (RemoteException e) {
1530            Log.e(TAG, "Dead object in stopBluetoothSco", e);
1531        }
1532    }
1533
1534    /**
1535     * Request use of Bluetooth SCO headset for communications.
1536     * <p>
1537     * This method should only be used by applications that replace the platform-wide
1538     * management of audio settings or the main telephony application.
1539     *
1540     * @param on set <var>true</var> to use bluetooth SCO for communications;
1541     *               <var>false</var> to not use bluetooth SCO for communications
1542     */
1543    public void setBluetoothScoOn(boolean on){
1544        IAudioService service = getService();
1545        try {
1546            service.setBluetoothScoOn(on);
1547        } catch (RemoteException e) {
1548            Log.e(TAG, "Dead object in setBluetoothScoOn", e);
1549        }
1550    }
1551
1552    /**
1553     * Checks whether communications use Bluetooth SCO.
1554     *
1555     * @return true if SCO is used for communications;
1556     *         false if otherwise
1557     */
1558    public boolean isBluetoothScoOn() {
1559        IAudioService service = getService();
1560        try {
1561            return service.isBluetoothScoOn();
1562        } catch (RemoteException e) {
1563            Log.e(TAG, "Dead object in isBluetoothScoOn", e);
1564            return false;
1565        }
1566    }
1567
1568    /**
1569     * @param on set <var>true</var> to route A2DP audio to/from Bluetooth
1570     *           headset; <var>false</var> disable A2DP audio
1571     * @deprecated Do not use.
1572     */
1573    @Deprecated public void setBluetoothA2dpOn(boolean on){
1574    }
1575
1576    /**
1577     * Checks whether A2DP audio routing to the Bluetooth headset is on or off.
1578     *
1579     * @return true if A2DP audio is being routed to/from Bluetooth headset;
1580     *         false if otherwise
1581     */
1582    public boolean isBluetoothA2dpOn() {
1583        if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_BLUETOOTH_A2DP,"")
1584            == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
1585            return false;
1586        } else {
1587            return true;
1588        }
1589    }
1590
1591    /**
1592     * Sets audio routing to the wired headset on or off.
1593     *
1594     * @param on set <var>true</var> to route audio to/from wired
1595     *           headset; <var>false</var> disable wired headset audio
1596     * @deprecated Do not use.
1597     */
1598    @Deprecated public void setWiredHeadsetOn(boolean on){
1599    }
1600
1601    /**
1602     * Checks whether a wired headset is connected or not.
1603     * <p>This is not a valid indication that audio playback is
1604     * actually over the wired headset as audio routing depends on other conditions.
1605     *
1606     * @return true if a wired headset is connected.
1607     *         false if otherwise
1608     * @deprecated Use only to check is a headset is connected or not.
1609     */
1610    public boolean isWiredHeadsetOn() {
1611        if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADSET,"")
1612                == AudioSystem.DEVICE_STATE_UNAVAILABLE &&
1613            AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE,"")
1614                == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
1615            return false;
1616        } else {
1617            return true;
1618        }
1619    }
1620
1621    /**
1622     * Sets the microphone mute on or off.
1623     * <p>
1624     * This method should only be used by applications that replace the platform-wide
1625     * management of audio settings or the main telephony application.
1626     *
1627     * @param on set <var>true</var> to mute the microphone;
1628     *           <var>false</var> to turn mute off
1629     */
1630    public void setMicrophoneMute(boolean on){
1631        IAudioService service = getService();
1632        try {
1633            service.setMicrophoneMute(on, mContext.getOpPackageName());
1634        } catch (RemoteException e) {
1635            Log.e(TAG, "Dead object in setMicrophoneMute", e);
1636        }
1637    }
1638
1639    /**
1640     * Checks whether the microphone mute is on or off.
1641     *
1642     * @return true if microphone is muted, false if it's not
1643     */
1644    public boolean isMicrophoneMute() {
1645        return AudioSystem.isMicrophoneMuted();
1646    }
1647
1648    /**
1649     * Sets the audio mode.
1650     * <p>
1651     * The audio mode encompasses audio routing AND the behavior of
1652     * the telephony layer. Therefore this method should only be used by applications that
1653     * replace the platform-wide management of audio settings or the main telephony application.
1654     * In particular, the {@link #MODE_IN_CALL} mode should only be used by the telephony
1655     * application when it places a phone call, as it will cause signals from the radio layer
1656     * to feed the platform mixer.
1657     *
1658     * @param mode  the requested audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
1659     *              {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
1660     *              Informs the HAL about the current audio state so that
1661     *              it can route the audio appropriately.
1662     */
1663    public void setMode(int mode) {
1664        IAudioService service = getService();
1665        try {
1666            service.setMode(mode, mICallBack);
1667        } catch (RemoteException e) {
1668            Log.e(TAG, "Dead object in setMode", e);
1669        }
1670    }
1671
1672    /**
1673     * Returns the current audio mode.
1674     *
1675     * @return      the current audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
1676     *              {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
1677     *              Returns the current current audio state from the HAL.
1678     */
1679    public int getMode() {
1680        IAudioService service = getService();
1681        try {
1682            return service.getMode();
1683        } catch (RemoteException e) {
1684            Log.e(TAG, "Dead object in getMode", e);
1685            return MODE_INVALID;
1686        }
1687    }
1688
1689    /* modes for setMode/getMode/setRoute/getRoute */
1690    /**
1691     * Audio harware modes.
1692     */
1693    /**
1694     * Invalid audio mode.
1695     */
1696    public static final int MODE_INVALID            = AudioSystem.MODE_INVALID;
1697    /**
1698     * Current audio mode. Used to apply audio routing to current mode.
1699     */
1700    public static final int MODE_CURRENT            = AudioSystem.MODE_CURRENT;
1701    /**
1702     * Normal audio mode: not ringing and no call established.
1703     */
1704    public static final int MODE_NORMAL             = AudioSystem.MODE_NORMAL;
1705    /**
1706     * Ringing audio mode. An incoming is being signaled.
1707     */
1708    public static final int MODE_RINGTONE           = AudioSystem.MODE_RINGTONE;
1709    /**
1710     * In call audio mode. A telephony call is established.
1711     */
1712    public static final int MODE_IN_CALL            = AudioSystem.MODE_IN_CALL;
1713    /**
1714     * In communication audio mode. An audio/video chat or VoIP call is established.
1715     */
1716    public static final int MODE_IN_COMMUNICATION   = AudioSystem.MODE_IN_COMMUNICATION;
1717
1718    /* Routing bits for setRouting/getRouting API */
1719    /**
1720     * Routing audio output to earpiece
1721     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1722     * setBluetoothScoOn() methods instead.
1723     */
1724    @Deprecated public static final int ROUTE_EARPIECE          = AudioSystem.ROUTE_EARPIECE;
1725    /**
1726     * Routing audio output to speaker
1727     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1728     * setBluetoothScoOn() methods instead.
1729     */
1730    @Deprecated public static final int ROUTE_SPEAKER           = AudioSystem.ROUTE_SPEAKER;
1731    /**
1732     * @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
1733     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1734     * setBluetoothScoOn() methods instead.
1735     */
1736    @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
1737    /**
1738     * Routing audio output to bluetooth SCO
1739     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1740     * setBluetoothScoOn() methods instead.
1741     */
1742    @Deprecated public static final int ROUTE_BLUETOOTH_SCO     = AudioSystem.ROUTE_BLUETOOTH_SCO;
1743    /**
1744     * Routing audio output to headset
1745     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1746     * setBluetoothScoOn() methods instead.
1747     */
1748    @Deprecated public static final int ROUTE_HEADSET           = AudioSystem.ROUTE_HEADSET;
1749    /**
1750     * Routing audio output to bluetooth A2DP
1751     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1752     * setBluetoothScoOn() methods instead.
1753     */
1754    @Deprecated public static final int ROUTE_BLUETOOTH_A2DP    = AudioSystem.ROUTE_BLUETOOTH_A2DP;
1755    /**
1756     * Used for mask parameter of {@link #setRouting(int,int,int)}.
1757     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1758     * setBluetoothScoOn() methods instead.
1759     */
1760    @Deprecated public static final int ROUTE_ALL               = AudioSystem.ROUTE_ALL;
1761
1762    /**
1763     * Sets the audio routing for a specified mode
1764     *
1765     * @param mode   audio mode to change route. E.g., MODE_RINGTONE.
1766     * @param routes bit vector of routes requested, created from one or
1767     *               more of ROUTE_xxx types. Set bits indicate that route should be on
1768     * @param mask   bit vector of routes to change, created from one or more of
1769     * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
1770     *
1771     * @deprecated   Do not set audio routing directly, use setSpeakerphoneOn(),
1772     * setBluetoothScoOn() methods instead.
1773     */
1774    @Deprecated
1775    public void setRouting(int mode, int routes, int mask) {
1776    }
1777
1778    /**
1779     * Returns the current audio routing bit vector for a specified mode.
1780     *
1781     * @param mode audio mode to get route (e.g., MODE_RINGTONE)
1782     * @return an audio route bit vector that can be compared with ROUTE_xxx
1783     * bits
1784     * @deprecated   Do not query audio routing directly, use isSpeakerphoneOn(),
1785     * isBluetoothScoOn(), isBluetoothA2dpOn() and isWiredHeadsetOn() methods instead.
1786     */
1787    @Deprecated
1788    public int getRouting(int mode) {
1789        return -1;
1790    }
1791
1792    /**
1793     * Checks whether any music is active.
1794     *
1795     * @return true if any music tracks are active.
1796     */
1797    public boolean isMusicActive() {
1798        return AudioSystem.isStreamActive(STREAM_MUSIC, 0);
1799    }
1800
1801    /**
1802     * @hide
1803     * Checks whether any music or media is actively playing on a remote device (e.g. wireless
1804     *   display). Note that BT audio sinks are not considered remote devices.
1805     * @return true if {@link AudioManager#STREAM_MUSIC} is active on a remote device
1806     */
1807    public boolean isMusicActiveRemotely() {
1808        return AudioSystem.isStreamActiveRemotely(STREAM_MUSIC, 0);
1809    }
1810
1811    /**
1812     * @hide
1813     * Checks whether the current audio focus is exclusive.
1814     * @return true if the top of the audio focus stack requested focus
1815     *     with {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE}
1816     */
1817    public boolean isAudioFocusExclusive() {
1818        IAudioService service = getService();
1819        try {
1820            return service.getCurrentAudioFocus() == AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE;
1821        } catch (RemoteException e) {
1822            Log.e(TAG, "Dead object in isAudioFocusExclusive()", e);
1823            return false;
1824        }
1825    }
1826
1827    /**
1828     * Return a new audio session identifier not associated with any player or effect.
1829     * An audio session identifier is a system wide unique identifier for a set of audio streams
1830     * (one or more mixed together).
1831     * <p>The primary use of the audio session ID is to associate audio effects to audio players,
1832     * such as {@link MediaPlayer} or {@link AudioTrack}: all audio effects sharing the same audio
1833     * session ID will be applied to the mixed audio content of the players that share the same
1834     * audio session.
1835     * <p>This method can for instance be used when creating one of the
1836     * {@link android.media.audiofx.AudioEffect} objects to define the audio session of the effect,
1837     * or to specify a session for a speech synthesis utterance
1838     * in {@link android.speech.tts.TextToSpeech.Engine}.
1839     * @return a new unclaimed and unused audio session identifier, or {@link #ERROR} when the
1840     *   system failed to generate a new session, a condition in which audio playback or recording
1841     *   will subsequently fail as well.
1842     */
1843    public int generateAudioSessionId() {
1844        int session = AudioSystem.newAudioSessionId();
1845        if (session > 0) {
1846            return session;
1847        } else {
1848            Log.e(TAG, "Failure to generate a new audio session ID");
1849            return ERROR;
1850        }
1851    }
1852
1853    /**
1854     * A special audio session ID to indicate that the audio session ID isn't known and the
1855     * framework should generate a new value. This can be used when building a new
1856     * {@link AudioTrack} instance with
1857     * {@link AudioTrack#AudioTrack(AudioAttributes, AudioFormat, int, int, int)}.
1858     */
1859    public static final int AUDIO_SESSION_ID_GENERATE = AudioSystem.AUDIO_SESSION_ALLOCATE;
1860
1861
1862    /*
1863     * Sets a generic audio configuration parameter. The use of these parameters
1864     * are platform dependant, see libaudio
1865     *
1866     * ** Temporary interface - DO NOT USE
1867     *
1868     * TODO: Replace with a more generic key:value get/set mechanism
1869     *
1870     * param key   name of parameter to set. Must not be null.
1871     * param value value of parameter. Must not be null.
1872     */
1873    /**
1874     * @hide
1875     * @deprecated Use {@link #setParameters(String)} instead
1876     */
1877    @Deprecated public void setParameter(String key, String value) {
1878        setParameters(key+"="+value);
1879    }
1880
1881    /**
1882     * Sets a variable number of parameter values to audio hardware.
1883     *
1884     * @param keyValuePairs list of parameters key value pairs in the form:
1885     *    key1=value1;key2=value2;...
1886     *
1887     */
1888    public void setParameters(String keyValuePairs) {
1889        AudioSystem.setParameters(keyValuePairs);
1890    }
1891
1892    /**
1893     * Gets a variable number of parameter values from audio hardware.
1894     *
1895     * @param keys list of parameters
1896     * @return list of parameters key value pairs in the form:
1897     *    key1=value1;key2=value2;...
1898     */
1899    public String getParameters(String keys) {
1900        return AudioSystem.getParameters(keys);
1901    }
1902
1903    /* Sound effect identifiers */
1904    /**
1905     * Keyboard and direction pad click sound
1906     * @see #playSoundEffect(int)
1907     */
1908    public static final int FX_KEY_CLICK = 0;
1909    /**
1910     * Focus has moved up
1911     * @see #playSoundEffect(int)
1912     */
1913    public static final int FX_FOCUS_NAVIGATION_UP = 1;
1914    /**
1915     * Focus has moved down
1916     * @see #playSoundEffect(int)
1917     */
1918    public static final int FX_FOCUS_NAVIGATION_DOWN = 2;
1919    /**
1920     * Focus has moved left
1921     * @see #playSoundEffect(int)
1922     */
1923    public static final int FX_FOCUS_NAVIGATION_LEFT = 3;
1924    /**
1925     * Focus has moved right
1926     * @see #playSoundEffect(int)
1927     */
1928    public static final int FX_FOCUS_NAVIGATION_RIGHT = 4;
1929    /**
1930     * IME standard keypress sound
1931     * @see #playSoundEffect(int)
1932     */
1933    public static final int FX_KEYPRESS_STANDARD = 5;
1934    /**
1935     * IME spacebar keypress sound
1936     * @see #playSoundEffect(int)
1937     */
1938    public static final int FX_KEYPRESS_SPACEBAR = 6;
1939    /**
1940     * IME delete keypress sound
1941     * @see #playSoundEffect(int)
1942     */
1943    public static final int FX_KEYPRESS_DELETE = 7;
1944    /**
1945     * IME return_keypress sound
1946     * @see #playSoundEffect(int)
1947     */
1948    public static final int FX_KEYPRESS_RETURN = 8;
1949
1950    /**
1951     * Invalid keypress sound
1952     * @see #playSoundEffect(int)
1953     */
1954    public static final int FX_KEYPRESS_INVALID = 9;
1955    /**
1956     * @hide Number of sound effects
1957     */
1958    public static final int NUM_SOUND_EFFECTS = 10;
1959
1960    /**
1961     * Plays a sound effect (Key clicks, lid open/close...)
1962     * @param effectType The type of sound effect. One of
1963     *            {@link #FX_KEY_CLICK},
1964     *            {@link #FX_FOCUS_NAVIGATION_UP},
1965     *            {@link #FX_FOCUS_NAVIGATION_DOWN},
1966     *            {@link #FX_FOCUS_NAVIGATION_LEFT},
1967     *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
1968     *            {@link #FX_KEYPRESS_STANDARD},
1969     *            {@link #FX_KEYPRESS_SPACEBAR},
1970     *            {@link #FX_KEYPRESS_DELETE},
1971     *            {@link #FX_KEYPRESS_RETURN},
1972     *            {@link #FX_KEYPRESS_INVALID},
1973     * NOTE: This version uses the UI settings to determine
1974     * whether sounds are heard or not.
1975     */
1976    public void  playSoundEffect(int effectType) {
1977        if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
1978            return;
1979        }
1980
1981        if (!querySoundEffectsEnabled(Process.myUserHandle().getIdentifier())) {
1982            return;
1983        }
1984
1985        IAudioService service = getService();
1986        try {
1987            service.playSoundEffect(effectType);
1988        } catch (RemoteException e) {
1989            Log.e(TAG, "Dead object in playSoundEffect"+e);
1990        }
1991    }
1992
1993    /**
1994     * Plays a sound effect (Key clicks, lid open/close...)
1995     * @param effectType The type of sound effect. One of
1996     *            {@link #FX_KEY_CLICK},
1997     *            {@link #FX_FOCUS_NAVIGATION_UP},
1998     *            {@link #FX_FOCUS_NAVIGATION_DOWN},
1999     *            {@link #FX_FOCUS_NAVIGATION_LEFT},
2000     *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
2001     *            {@link #FX_KEYPRESS_STANDARD},
2002     *            {@link #FX_KEYPRESS_SPACEBAR},
2003     *            {@link #FX_KEYPRESS_DELETE},
2004     *            {@link #FX_KEYPRESS_RETURN},
2005     *            {@link #FX_KEYPRESS_INVALID},
2006     * @param userId The current user to pull sound settings from
2007     * NOTE: This version uses the UI settings to determine
2008     * whether sounds are heard or not.
2009     * @hide
2010     */
2011    public void  playSoundEffect(int effectType, int userId) {
2012        if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
2013            return;
2014        }
2015
2016        if (!querySoundEffectsEnabled(userId)) {
2017            return;
2018        }
2019
2020        IAudioService service = getService();
2021        try {
2022            service.playSoundEffect(effectType);
2023        } catch (RemoteException e) {
2024            Log.e(TAG, "Dead object in playSoundEffect"+e);
2025        }
2026    }
2027
2028    /**
2029     * Plays a sound effect (Key clicks, lid open/close...)
2030     * @param effectType The type of sound effect. One of
2031     *            {@link #FX_KEY_CLICK},
2032     *            {@link #FX_FOCUS_NAVIGATION_UP},
2033     *            {@link #FX_FOCUS_NAVIGATION_DOWN},
2034     *            {@link #FX_FOCUS_NAVIGATION_LEFT},
2035     *            {@link #FX_FOCUS_NAVIGATION_RIGHT},
2036     *            {@link #FX_KEYPRESS_STANDARD},
2037     *            {@link #FX_KEYPRESS_SPACEBAR},
2038     *            {@link #FX_KEYPRESS_DELETE},
2039     *            {@link #FX_KEYPRESS_RETURN},
2040     *            {@link #FX_KEYPRESS_INVALID},
2041     * @param volume Sound effect volume.
2042     * The volume value is a raw scalar so UI controls should be scaled logarithmically.
2043     * If a volume of -1 is specified, the AudioManager.STREAM_MUSIC stream volume minus 3dB will be used.
2044     * NOTE: This version is for applications that have their own
2045     * settings panel for enabling and controlling volume.
2046     */
2047    public void  playSoundEffect(int effectType, float volume) {
2048        if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
2049            return;
2050        }
2051
2052        IAudioService service = getService();
2053        try {
2054            service.playSoundEffectVolume(effectType, volume);
2055        } catch (RemoteException e) {
2056            Log.e(TAG, "Dead object in playSoundEffect"+e);
2057        }
2058    }
2059
2060    /**
2061     * Settings has an in memory cache, so this is fast.
2062     */
2063    private boolean querySoundEffectsEnabled(int user) {
2064        return Settings.System.getIntForUser(mContext.getContentResolver(),
2065                Settings.System.SOUND_EFFECTS_ENABLED, 0, user) != 0;
2066    }
2067
2068
2069    /**
2070     *  Load Sound effects.
2071     *  This method must be called when sound effects are enabled.
2072     */
2073    public void loadSoundEffects() {
2074        IAudioService service = getService();
2075        try {
2076            service.loadSoundEffects();
2077        } catch (RemoteException e) {
2078            Log.e(TAG, "Dead object in loadSoundEffects"+e);
2079        }
2080    }
2081
2082    /**
2083     *  Unload Sound effects.
2084     *  This method can be called to free some memory when
2085     *  sound effects are disabled.
2086     */
2087    public void unloadSoundEffects() {
2088        IAudioService service = getService();
2089        try {
2090            service.unloadSoundEffects();
2091        } catch (RemoteException e) {
2092            Log.e(TAG, "Dead object in unloadSoundEffects"+e);
2093        }
2094    }
2095
2096    /**
2097     * @hide
2098     * Used to indicate no audio focus has been gained or lost.
2099     */
2100    public static final int AUDIOFOCUS_NONE = 0;
2101
2102    /**
2103     * Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
2104     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2105     * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2106     */
2107    public static final int AUDIOFOCUS_GAIN = 1;
2108    /**
2109     * Used to indicate a temporary gain or request of audio focus, anticipated to last a short
2110     * amount of time. Examples of temporary changes are the playback of driving directions, or an
2111     * event notification.
2112     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2113     * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2114     */
2115    public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
2116    /**
2117     * Used to indicate a temporary request of audio focus, anticipated to last a short
2118     * amount of time, and where it is acceptable for other audio applications to keep playing
2119     * after having lowered their output level (also referred to as "ducking").
2120     * Examples of temporary changes are the playback of driving directions where playback of music
2121     * in the background is acceptable.
2122     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2123     * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2124     */
2125    public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;
2126    /**
2127     * Used to indicate a temporary request of audio focus, anticipated to last a short
2128     * amount of time, during which no other applications, or system components, should play
2129     * anything. Examples of exclusive and transient audio focus requests are voice
2130     * memo recording and speech recognition, during which the system shouldn't play any
2131     * notifications, and media playback should have paused.
2132     * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2133     */
2134    public static final int AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE = 4;
2135    /**
2136     * Used to indicate a loss of audio focus of unknown duration.
2137     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2138     */
2139    public static final int AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN;
2140    /**
2141     * Used to indicate a transient loss of audio focus.
2142     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2143     */
2144    public static final int AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT;
2145    /**
2146     * Used to indicate a transient loss of audio focus where the loser of the audio focus can
2147     * lower its output volume if it wants to continue playing (also referred to as "ducking"), as
2148     * the new focus owner doesn't require others to be silent.
2149     * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2150     */
2151    public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
2152            -1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
2153
2154    /**
2155     * Interface definition for a callback to be invoked when the audio focus of the system is
2156     * updated.
2157     */
2158    public interface OnAudioFocusChangeListener {
2159        /**
2160         * Called on the listener to notify it the audio focus for this listener has been changed.
2161         * The focusChange value indicates whether the focus was gained,
2162         * whether the focus was lost, and whether that loss is transient, or whether the new focus
2163         * holder will hold it for an unknown amount of time.
2164         * When losing focus, listeners can use the focus change information to decide what
2165         * behavior to adopt when losing focus. A music player could for instance elect to lower
2166         * the volume of its music stream (duck) for transient focus losses, and pause otherwise.
2167         * @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
2168         *   {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
2169         *   and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
2170         */
2171        public void onAudioFocusChange(int focusChange);
2172    }
2173
2174    /**
2175     * Map to convert focus event listener IDs, as used in the AudioService audio focus stack,
2176     * to actual listener objects.
2177     */
2178    private final HashMap<String, OnAudioFocusChangeListener> mAudioFocusIdListenerMap =
2179            new HashMap<String, OnAudioFocusChangeListener>();
2180    /**
2181     * Lock to prevent concurrent changes to the list of focus listeners for this AudioManager
2182     * instance.
2183     */
2184    private final Object mFocusListenerLock = new Object();
2185
2186    private OnAudioFocusChangeListener findFocusListener(String id) {
2187        return mAudioFocusIdListenerMap.get(id);
2188    }
2189
2190    /**
2191     * Handler for audio focus events coming from the audio service.
2192     */
2193    private final FocusEventHandlerDelegate mAudioFocusEventHandlerDelegate =
2194            new FocusEventHandlerDelegate();
2195
2196    /**
2197     * Helper class to handle the forwarding of audio focus events to the appropriate listener
2198     */
2199    private class FocusEventHandlerDelegate {
2200        private final Handler mHandler;
2201
2202        FocusEventHandlerDelegate() {
2203            Looper looper;
2204            if ((looper = Looper.myLooper()) == null) {
2205                looper = Looper.getMainLooper();
2206            }
2207
2208            if (looper != null) {
2209                // implement the event handler delegate to receive audio focus events
2210                mHandler = new Handler(looper) {
2211                    @Override
2212                    public void handleMessage(Message msg) {
2213                        OnAudioFocusChangeListener listener = null;
2214                        synchronized(mFocusListenerLock) {
2215                            listener = findFocusListener((String)msg.obj);
2216                        }
2217                        if (listener != null) {
2218                            Log.d(TAG, "AudioManager dispatching onAudioFocusChange("
2219                                    + msg.what + ") for " + msg.obj);
2220                            listener.onAudioFocusChange(msg.what);
2221                        }
2222                    }
2223                };
2224            } else {
2225                mHandler = null;
2226            }
2227        }
2228
2229        Handler getHandler() {
2230            return mHandler;
2231        }
2232    }
2233
2234    private final IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
2235
2236        public void dispatchAudioFocusChange(int focusChange, String id) {
2237            Message m = mAudioFocusEventHandlerDelegate.getHandler().obtainMessage(focusChange, id);
2238            mAudioFocusEventHandlerDelegate.getHandler().sendMessage(m);
2239        }
2240
2241    };
2242
2243    private String getIdForAudioFocusListener(OnAudioFocusChangeListener l) {
2244        if (l == null) {
2245            return new String(this.toString());
2246        } else {
2247            return new String(this.toString() + l.toString());
2248        }
2249    }
2250
2251    /**
2252     * @hide
2253     * Registers a listener to be called when audio focus changes. Calling this method is optional
2254     * before calling {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, as it
2255     * will register the listener as well if it wasn't registered already.
2256     * @param l the listener to be notified of audio focus changes.
2257     */
2258    public void registerAudioFocusListener(OnAudioFocusChangeListener l) {
2259        synchronized(mFocusListenerLock) {
2260            if (mAudioFocusIdListenerMap.containsKey(getIdForAudioFocusListener(l))) {
2261                return;
2262            }
2263            mAudioFocusIdListenerMap.put(getIdForAudioFocusListener(l), l);
2264        }
2265    }
2266
2267    /**
2268     * @hide
2269     * Causes the specified listener to not be called anymore when focus is gained or lost.
2270     * @param l the listener to unregister.
2271     */
2272    public void unregisterAudioFocusListener(OnAudioFocusChangeListener l) {
2273
2274        // remove locally
2275        synchronized(mFocusListenerLock) {
2276            mAudioFocusIdListenerMap.remove(getIdForAudioFocusListener(l));
2277        }
2278    }
2279
2280
2281    /**
2282     * A failed focus change request.
2283     */
2284    public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
2285    /**
2286     * A successful focus change request.
2287     */
2288    public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
2289     /**
2290      * @hide
2291      * A focus change request whose granting is delayed: the request was successful, but the
2292      * requester will only be granted audio focus once the condition that prevented immediate
2293      * granting has ended.
2294      * See {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2295      */
2296    public static final int AUDIOFOCUS_REQUEST_DELAYED = 2;
2297
2298
2299    /**
2300     *  Request audio focus.
2301     *  Send a request to obtain the audio focus
2302     *  @param l the listener to be notified of audio focus changes
2303     *  @param streamType the main audio stream type affected by the focus request
2304     *  @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
2305     *      is temporary, and focus will be abandonned shortly. Examples of transient requests are
2306     *      for the playback of driving directions, or notifications sounds.
2307     *      Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
2308     *      the previous focus owner to keep playing if it ducks its audio output.
2309     *      Alternatively use {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE} for a temporary request
2310     *      that benefits from the system not playing disruptive sounds like notifications, for
2311     *      usecases such as voice memo recording, or speech recognition.
2312     *      Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
2313     *      as the playback of a song or a video.
2314     *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
2315     */
2316    public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) {
2317        int status = AUDIOFOCUS_REQUEST_FAILED;
2318
2319        try {
2320            // status is guaranteed to be either AUDIOFOCUS_REQUEST_FAILED or
2321            // AUDIOFOCUS_REQUEST_GRANTED as focus is requested without the
2322            // AUDIOFOCUS_FLAG_DELAY_OK flag
2323            status = requestAudioFocus(l,
2324                    new AudioAttributes.Builder()
2325                            .setInternalLegacyStreamType(streamType).build(),
2326                    durationHint,
2327                    0 /* flags, legacy behavior */);
2328        } catch (IllegalArgumentException e) {
2329            Log.e(TAG, "Audio focus request denied due to ", e);
2330        }
2331
2332        return status;
2333    }
2334
2335    // when adding new flags, add them to the relevant AUDIOFOCUS_FLAGS_APPS or SYSTEM masks
2336    /**
2337     * @hide
2338     * Use this flag when requesting audio focus to indicate it is ok for the requester to not be
2339     * granted audio focus immediately (as indicated by {@link #AUDIOFOCUS_REQUEST_DELAYED}) when
2340     * the system is in a state where focus cannot change, but be granted focus later when
2341     * this condition ends.
2342     */
2343    @SystemApi
2344    public static final int AUDIOFOCUS_FLAG_DELAY_OK = 0x1 << 0;
2345    /**
2346     * @hide
2347     * Use this flag when requesting audio focus to indicate that the requester
2348     * will pause its media playback (if applicable) when losing audio focus with
2349     * {@link #AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}, rather than ducking.
2350     * <br>On some platforms, the ducking may be handled without the application being aware of it
2351     * (i.e. it will not transiently lose focus). For applications that for instance play spoken
2352     * content, such as audio book or podcast players, ducking may never be acceptable, and will
2353     * thus always pause. This flag enables them to be declared as such whenever they request focus.
2354     */
2355    @SystemApi
2356    public static final int AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS = 0x1 << 1;
2357    /**
2358     * @hide
2359     * Use this flag to lock audio focus so granting is temporarily disabled.
2360     * <br>This flag can only be used by owners of a registered
2361     * {@link android.media.audiopolicy.AudioPolicy} in
2362     * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int, AudioPolicy)}
2363     */
2364    @SystemApi
2365    public static final int AUDIOFOCUS_FLAG_LOCK     = 0x1 << 2;
2366    /** @hide */
2367    public static final int AUDIOFOCUS_FLAGS_APPS = AUDIOFOCUS_FLAG_DELAY_OK
2368            | AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS;
2369    /** @hide */
2370    public static final int AUDIOFOCUS_FLAGS_SYSTEM = AUDIOFOCUS_FLAG_DELAY_OK
2371            | AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS | AUDIOFOCUS_FLAG_LOCK;
2372
2373    /**
2374     * @hide
2375     * Request audio focus.
2376     * Send a request to obtain the audio focus. This method differs from
2377     * {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)} in that it can express
2378     * that the requester accepts delayed grants of audio focus.
2379     * @param l the listener to be notified of audio focus changes. It is not allowed to be null
2380     *     when the request is flagged with {@link #AUDIOFOCUS_FLAG_DELAY_OK}.
2381     * @param requestAttributes non null {@link AudioAttributes} describing the main reason for
2382     *     requesting audio focus.
2383     * @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
2384     *      is temporary, and focus will be abandonned shortly. Examples of transient requests are
2385     *      for the playback of driving directions, or notifications sounds.
2386     *      Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
2387     *      the previous focus owner to keep playing if it ducks its audio output.
2388     *      Alternatively use {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE} for a temporary request
2389     *      that benefits from the system not playing disruptive sounds like notifications, for
2390     *      usecases such as voice memo recording, or speech recognition.
2391     *      Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
2392     *      as the playback of a song or a video.
2393     * @param flags 0 or a combination of {link #AUDIOFOCUS_FLAG_DELAY_OK}
2394     *     and {@link #AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS}.
2395     *     <br>Use 0 when not using any flags for the request, which behaves like
2396     *     {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, where either audio
2397     *     focus is granted immediately, or the grant request fails because the system is in a
2398     *     state where focus cannot change (e.g. a phone call).
2399     * @return {@link #AUDIOFOCUS_REQUEST_FAILED}, {@link #AUDIOFOCUS_REQUEST_GRANTED}
2400     *     or {@link #AUDIOFOCUS_REQUEST_DELAYED}.
2401     *     The return value is never {@link #AUDIOFOCUS_REQUEST_DELAYED} when focus is requested
2402     *     without the {@link #AUDIOFOCUS_FLAG_DELAY_OK} flag.
2403     * @throws IllegalArgumentException
2404     */
2405    @SystemApi
2406    public int requestAudioFocus(OnAudioFocusChangeListener l,
2407            @NonNull AudioAttributes requestAttributes,
2408            int durationHint,
2409            int flags) throws IllegalArgumentException {
2410        if (flags != (flags & AUDIOFOCUS_FLAGS_APPS)) {
2411            throw new IllegalArgumentException("Invalid flags 0x"
2412                    + Integer.toHexString(flags).toUpperCase());
2413        }
2414        return requestAudioFocus(l, requestAttributes, durationHint,
2415                flags & AUDIOFOCUS_FLAGS_APPS,
2416                null /* no AudioPolicy*/);
2417    }
2418
2419    /**
2420     * @hide
2421     * Request or lock audio focus.
2422     * This method is to be used by system components that have registered an
2423     * {@link android.media.audiopolicy.AudioPolicy} to request audio focus, but also to "lock" it
2424     * so focus granting is temporarily disabled.
2425     * @param l see the description of the same parameter in
2426     *     {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2427     * @param requestAttributes non null {@link AudioAttributes} describing the main reason for
2428     *     requesting audio focus.
2429     * @param durationHint see the description of the same parameter in
2430     *     {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2431     * @param flags 0 or a combination of {link #AUDIOFOCUS_FLAG_DELAY_OK},
2432     *     {@link #AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS}, and {@link #AUDIOFOCUS_FLAG_LOCK}.
2433     *     <br>Use 0 when not using any flags for the request, which behaves like
2434     *     {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, where either audio
2435     *     focus is granted immediately, or the grant request fails because the system is in a
2436     *     state where focus cannot change (e.g. a phone call).
2437     * @param ap a registered {@link android.media.audiopolicy.AudioPolicy} instance when locking
2438     *     focus, or null.
2439     * @return see the description of the same return value in
2440     *     {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2441     * @throws IllegalArgumentException
2442     */
2443    @SystemApi
2444    public int requestAudioFocus(OnAudioFocusChangeListener l,
2445            @NonNull AudioAttributes requestAttributes,
2446            int durationHint,
2447            int flags,
2448            AudioPolicy ap) throws IllegalArgumentException {
2449        // parameter checking
2450        if (requestAttributes == null) {
2451            throw new IllegalArgumentException("Illegal null AudioAttributes argument");
2452        }
2453        if ((durationHint < AUDIOFOCUS_GAIN) ||
2454                (durationHint > AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE)) {
2455            throw new IllegalArgumentException("Invalid duration hint");
2456        }
2457        if (flags != (flags & AUDIOFOCUS_FLAGS_SYSTEM)) {
2458            throw new IllegalArgumentException("Illegal flags 0x"
2459                + Integer.toHexString(flags).toUpperCase());
2460        }
2461        if (((flags & AUDIOFOCUS_FLAG_DELAY_OK) == AUDIOFOCUS_FLAG_DELAY_OK) && (l == null)) {
2462            throw new IllegalArgumentException(
2463                    "Illegal null focus listener when flagged as accepting delayed focus grant");
2464        }
2465        if (((flags & AUDIOFOCUS_FLAG_LOCK) == AUDIOFOCUS_FLAG_LOCK) && (ap == null)) {
2466            throw new IllegalArgumentException(
2467                    "Illegal null audio policy when locking audio focus");
2468        }
2469
2470        int status = AUDIOFOCUS_REQUEST_FAILED;
2471        registerAudioFocusListener(l);
2472        IAudioService service = getService();
2473        try {
2474            status = service.requestAudioFocus(requestAttributes, durationHint, mICallBack,
2475                    mAudioFocusDispatcher, getIdForAudioFocusListener(l),
2476                    mContext.getOpPackageName() /* package name */, flags,
2477                    ap != null ? ap.cb() : null);
2478        } catch (RemoteException e) {
2479            Log.e(TAG, "Can't call requestAudioFocus() on AudioService:", e);
2480        }
2481        return status;
2482    }
2483
2484    /**
2485     * @hide
2486     * Used internally by telephony package to request audio focus. Will cause the focus request
2487     * to be associated with the "voice communication" identifier only used in AudioService
2488     * to identify this use case.
2489     * @param streamType use STREAM_RING for focus requests when ringing, VOICE_CALL for
2490     *    the establishment of the call
2491     * @param durationHint the type of focus request. AUDIOFOCUS_GAIN_TRANSIENT is recommended so
2492     *    media applications resume after a call
2493     */
2494    public void requestAudioFocusForCall(int streamType, int durationHint) {
2495        IAudioService service = getService();
2496        try {
2497            service.requestAudioFocus(new AudioAttributes.Builder()
2498                        .setInternalLegacyStreamType(streamType).build(),
2499                    durationHint, mICallBack, null,
2500                    MediaFocusControl.IN_VOICE_COMM_FOCUS_ID,
2501                    mContext.getOpPackageName(),
2502                    AUDIOFOCUS_FLAG_LOCK,
2503                    null /* policy token */);
2504        } catch (RemoteException e) {
2505            Log.e(TAG, "Can't call requestAudioFocusForCall() on AudioService:", e);
2506        }
2507    }
2508
2509    /**
2510     * @hide
2511     * Used internally by telephony package to abandon audio focus, typically after a call or
2512     * when ringing ends and the call is rejected or not answered.
2513     * Should match one or more calls to {@link #requestAudioFocusForCall(int, int)}.
2514     */
2515    public void abandonAudioFocusForCall() {
2516        IAudioService service = getService();
2517        try {
2518            service.abandonAudioFocus(null, MediaFocusControl.IN_VOICE_COMM_FOCUS_ID,
2519                    null /*AudioAttributes, legacy behavior*/);
2520        } catch (RemoteException e) {
2521            Log.e(TAG, "Can't call abandonAudioFocusForCall() on AudioService:", e);
2522        }
2523    }
2524
2525    /**
2526     *  Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
2527     *  @param l the listener with which focus was requested.
2528     *  @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
2529     */
2530    public int abandonAudioFocus(OnAudioFocusChangeListener l) {
2531        return abandonAudioFocus(l, null /*AudioAttributes, legacy behavior*/);
2532    }
2533
2534    /**
2535     * @hide
2536     * Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
2537     *  @param l the listener with which focus was requested.
2538     * @param aa the {@link AudioAttributes} with which audio focus was requested
2539     * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
2540     */
2541    @SystemApi
2542    public int abandonAudioFocus(OnAudioFocusChangeListener l, AudioAttributes aa) {
2543        int status = AUDIOFOCUS_REQUEST_FAILED;
2544        unregisterAudioFocusListener(l);
2545        IAudioService service = getService();
2546        try {
2547            status = service.abandonAudioFocus(mAudioFocusDispatcher,
2548                    getIdForAudioFocusListener(l), aa);
2549        } catch (RemoteException e) {
2550            Log.e(TAG, "Can't call abandonAudioFocus() on AudioService:", e);
2551        }
2552        return status;
2553    }
2554
2555    //====================================================================
2556    // Remote Control
2557    /**
2558     * Register a component to be the sole receiver of MEDIA_BUTTON intents.
2559     * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
2560     *      that will receive the media button intent. This broadcast receiver must be declared
2561     *      in the application manifest. The package of the component must match that of
2562     *      the context you're registering from.
2563     * @deprecated Use {@link MediaSession#setMediaButtonReceiver(PendingIntent)} instead.
2564     */
2565    @Deprecated
2566    public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
2567        if (eventReceiver == null) {
2568            return;
2569        }
2570        if (!eventReceiver.getPackageName().equals(mContext.getPackageName())) {
2571            Log.e(TAG, "registerMediaButtonEventReceiver() error: " +
2572                    "receiver and context package names don't match");
2573            return;
2574        }
2575        // construct a PendingIntent for the media button and register it
2576        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2577        //     the associated intent will be handled by the component being registered
2578        mediaButtonIntent.setComponent(eventReceiver);
2579        PendingIntent pi = PendingIntent.getBroadcast(mContext,
2580                0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
2581        registerMediaButtonIntent(pi, eventReceiver);
2582    }
2583
2584    /**
2585     * Register a component to be the sole receiver of MEDIA_BUTTON intents.  This is like
2586     * {@link #registerMediaButtonEventReceiver(android.content.ComponentName)}, but allows
2587     * the buttons to go to any PendingIntent.  Note that you should only use this form if
2588     * you know you will continue running for the full time until unregistering the
2589     * PendingIntent.
2590     * @param eventReceiver target that will receive media button intents.  The PendingIntent
2591     * will be sent an {@link Intent#ACTION_MEDIA_BUTTON} event when a media button action
2592     * occurs, with {@link Intent#EXTRA_KEY_EVENT} added and holding the key code of the
2593     * media button that was pressed.
2594     * @deprecated Use {@link MediaSession#setMediaButtonReceiver(PendingIntent)} instead.
2595     */
2596    @Deprecated
2597    public void registerMediaButtonEventReceiver(PendingIntent eventReceiver) {
2598        if (eventReceiver == null) {
2599            return;
2600        }
2601        registerMediaButtonIntent(eventReceiver, null);
2602    }
2603
2604    /**
2605     * @hide
2606     * no-op if (pi == null) or (eventReceiver == null)
2607     */
2608    public void registerMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {
2609        if (pi == null) {
2610            Log.e(TAG, "Cannot call registerMediaButtonIntent() with a null parameter");
2611            return;
2612        }
2613        MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(mContext);
2614        helper.addMediaButtonListener(pi, eventReceiver, mContext);
2615    }
2616
2617    /**
2618     * Unregister the receiver of MEDIA_BUTTON intents.
2619     * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
2620     *      that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.
2621     * @deprecated Use {@link MediaSession} instead.
2622     */
2623    @Deprecated
2624    public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
2625        if (eventReceiver == null) {
2626            return;
2627        }
2628        // construct a PendingIntent for the media button and unregister it
2629        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2630        //     the associated intent will be handled by the component being registered
2631        mediaButtonIntent.setComponent(eventReceiver);
2632        PendingIntent pi = PendingIntent.getBroadcast(mContext,
2633                0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
2634        unregisterMediaButtonIntent(pi);
2635    }
2636
2637    /**
2638     * Unregister the receiver of MEDIA_BUTTON intents.
2639     * @param eventReceiver same PendingIntent that was registed with
2640     *      {@link #registerMediaButtonEventReceiver(PendingIntent)}.
2641     * @deprecated Use {@link MediaSession} instead.
2642     */
2643    @Deprecated
2644    public void unregisterMediaButtonEventReceiver(PendingIntent eventReceiver) {
2645        if (eventReceiver == null) {
2646            return;
2647        }
2648        unregisterMediaButtonIntent(eventReceiver);
2649    }
2650
2651    /**
2652     * @hide
2653     */
2654    public void unregisterMediaButtonIntent(PendingIntent pi) {
2655        MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(mContext);
2656        helper.removeMediaButtonListener(pi);
2657    }
2658
2659    /**
2660     * Registers the remote control client for providing information to display on the remote
2661     * controls.
2662     * @param rcClient The remote control client from which remote controls will receive
2663     *      information to display.
2664     * @see RemoteControlClient
2665     * @deprecated Use {@link MediaSession} instead.
2666     */
2667    @Deprecated
2668    public void registerRemoteControlClient(RemoteControlClient rcClient) {
2669        if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
2670            return;
2671        }
2672        rcClient.registerWithSession(MediaSessionLegacyHelper.getHelper(mContext));
2673    }
2674
2675    /**
2676     * Unregisters the remote control client that was providing information to display on the
2677     * remote controls.
2678     * @param rcClient The remote control client to unregister.
2679     * @see #registerRemoteControlClient(RemoteControlClient)
2680     * @deprecated Use {@link MediaSession} instead.
2681     */
2682    @Deprecated
2683    public void unregisterRemoteControlClient(RemoteControlClient rcClient) {
2684        if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
2685            return;
2686        }
2687        rcClient.unregisterWithSession(MediaSessionLegacyHelper.getHelper(mContext));
2688    }
2689
2690    /**
2691     * Registers a {@link RemoteController} instance for it to receive media
2692     * metadata updates and playback state information from applications using
2693     * {@link RemoteControlClient}, and control their playback.
2694     * <p>
2695     * Registration requires the {@link OnClientUpdateListener} listener to be
2696     * one of the enabled notification listeners (see
2697     * {@link android.service.notification.NotificationListenerService}).
2698     *
2699     * @param rctlr the object to register.
2700     * @return true if the {@link RemoteController} was successfully registered,
2701     *         false if an error occurred, due to an internal system error, or
2702     *         insufficient permissions.
2703     * @deprecated Use
2704     *             {@link MediaSessionManager#addOnActiveSessionsChangedListener(android.media.session.MediaSessionManager.OnActiveSessionsChangedListener, ComponentName)}
2705     *             and {@link MediaController} instead.
2706     */
2707    @Deprecated
2708    public boolean registerRemoteController(RemoteController rctlr) {
2709        if (rctlr == null) {
2710            return false;
2711        }
2712        rctlr.startListeningToSessions();
2713        return true;
2714    }
2715
2716    /**
2717     * Unregisters a {@link RemoteController}, causing it to no longer receive
2718     * media metadata and playback state information, and no longer be capable
2719     * of controlling playback.
2720     *
2721     * @param rctlr the object to unregister.
2722     * @deprecated Use
2723     *             {@link MediaSessionManager#removeOnActiveSessionsChangedListener(android.media.session.MediaSessionManager.OnActiveSessionsChangedListener)}
2724     *             instead.
2725     */
2726    @Deprecated
2727    public void unregisterRemoteController(RemoteController rctlr) {
2728        if (rctlr == null) {
2729            return;
2730        }
2731        rctlr.stopListeningToSessions();
2732    }
2733
2734    /**
2735     * @hide
2736     * Registers a remote control display that will be sent information by remote control clients.
2737     * Use this method if your IRemoteControlDisplay is not going to display artwork, otherwise
2738     * use {@link #registerRemoteControlDisplay(IRemoteControlDisplay, int, int)} to pass the
2739     * artwork size directly, or
2740     * {@link #remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay, int, int)} later if artwork
2741     * is not yet needed.
2742     * <p>Registration requires the {@link Manifest.permission#MEDIA_CONTENT_CONTROL} permission.
2743     * @param rcd the IRemoteControlDisplay
2744     */
2745    public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {
2746        // passing a negative value for art work width and height as they are unknown at this stage
2747        registerRemoteControlDisplay(rcd, /*w*/-1, /*h*/ -1);
2748    }
2749
2750    /**
2751     * @hide
2752     * Registers a remote control display that will be sent information by remote control clients.
2753     * <p>Registration requires the {@link Manifest.permission#MEDIA_CONTENT_CONTROL} permission.
2754     * @param rcd
2755     * @param w the maximum width of the expected bitmap. Negative values indicate it is
2756     *   useless to send artwork.
2757     * @param h the maximum height of the expected bitmap. Negative values indicate it is
2758     *   useless to send artwork.
2759     */
2760    public void registerRemoteControlDisplay(IRemoteControlDisplay rcd, int w, int h) {
2761        if (rcd == null) {
2762            return;
2763        }
2764        IAudioService service = getService();
2765        try {
2766            service.registerRemoteControlDisplay(rcd, w, h);
2767        } catch (RemoteException e) {
2768            Log.e(TAG, "Dead object in registerRemoteControlDisplay " + e);
2769        }
2770    }
2771
2772    /**
2773     * @hide
2774     * Unregisters a remote control display that was sent information by remote control clients.
2775     * @param rcd
2776     */
2777    public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
2778        if (rcd == null) {
2779            return;
2780        }
2781        IAudioService service = getService();
2782        try {
2783            service.unregisterRemoteControlDisplay(rcd);
2784        } catch (RemoteException e) {
2785            Log.e(TAG, "Dead object in unregisterRemoteControlDisplay " + e);
2786        }
2787    }
2788
2789    /**
2790     * @hide
2791     * Sets the artwork size a remote control display expects when receiving bitmaps.
2792     * @param rcd
2793     * @param w the maximum width of the expected bitmap. Negative values indicate it is
2794     *   useless to send artwork.
2795     * @param h the maximum height of the expected bitmap. Negative values indicate it is
2796     *   useless to send artwork.
2797     */
2798    public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
2799        if (rcd == null) {
2800            return;
2801        }
2802        IAudioService service = getService();
2803        try {
2804            service.remoteControlDisplayUsesBitmapSize(rcd, w, h);
2805        } catch (RemoteException e) {
2806            Log.e(TAG, "Dead object in remoteControlDisplayUsesBitmapSize " + e);
2807        }
2808    }
2809
2810    /**
2811     * @hide
2812     * Controls whether a remote control display needs periodic checks of the RemoteControlClient
2813     * playback position to verify that the estimated position has not drifted from the actual
2814     * position. By default the check is not performed.
2815     * The IRemoteControlDisplay must have been previously registered for this to have any effect.
2816     * @param rcd the IRemoteControlDisplay for which the anti-drift mechanism will be enabled
2817     *     or disabled. No effect is null.
2818     * @param wantsSync if true, RemoteControlClient instances which expose their playback position
2819     *     to the framework will regularly compare the estimated playback position with the actual
2820     *     position, and will update the IRemoteControlDisplay implementation whenever a drift is
2821     *     detected.
2822     */
2823    public void remoteControlDisplayWantsPlaybackPositionSync(IRemoteControlDisplay rcd,
2824            boolean wantsSync) {
2825        if (rcd == null) {
2826            return;
2827        }
2828        IAudioService service = getService();
2829        try {
2830            service.remoteControlDisplayWantsPlaybackPositionSync(rcd, wantsSync);
2831        } catch (RemoteException e) {
2832            Log.e(TAG, "Dead object in remoteControlDisplayWantsPlaybackPositionSync " + e);
2833        }
2834    }
2835
2836    /**
2837     * @hide
2838     * Register the given {@link AudioPolicy}.
2839     * This call is synchronous and blocks until the registration process successfully completed
2840     * or failed to complete.
2841     * @param policy the non-null {@link AudioPolicy} to register.
2842     * @return {@link #ERROR} if there was an error communicating with the registration service
2843     *    or if the user doesn't have the required
2844     *    {@link android.Manifest.permission#MODIFY_AUDIO_ROUTING} permission,
2845     *    {@link #SUCCESS} otherwise.
2846     */
2847    @SystemApi
2848    public int registerAudioPolicy(@NonNull AudioPolicy policy) {
2849        if (policy == null) {
2850            throw new IllegalArgumentException("Illegal null AudioPolicy argument");
2851        }
2852        IAudioService service = getService();
2853        try {
2854            String regId = service.registerAudioPolicy(policy.getConfig(), policy.cb(),
2855                    policy.hasFocusListener());
2856            if (regId == null) {
2857                return ERROR;
2858            } else {
2859                policy.setRegistration(regId);
2860            }
2861            // successful registration
2862        } catch (RemoteException e) {
2863            Log.e(TAG, "Dead object in registerAudioPolicyAsync()", e);
2864            return ERROR;
2865        }
2866        return SUCCESS;
2867    }
2868
2869    /**
2870     * @hide
2871     * @param policy the non-null {@link AudioPolicy} to unregister.
2872     */
2873    @SystemApi
2874    public void unregisterAudioPolicyAsync(@NonNull AudioPolicy policy) {
2875        if (policy == null) {
2876            throw new IllegalArgumentException("Illegal null AudioPolicy argument");
2877        }
2878        IAudioService service = getService();
2879        try {
2880            service.unregisterAudioPolicyAsync(policy.cb());
2881            policy.setRegistration(null);
2882        } catch (RemoteException e) {
2883            Log.e(TAG, "Dead object in unregisterAudioPolicyAsync()", e);
2884        }
2885    }
2886
2887
2888    /**
2889     *  @hide
2890     *  Reload audio settings. This method is called by Settings backup
2891     *  agent when audio settings are restored and causes the AudioService
2892     *  to read and apply restored settings.
2893     */
2894    public void reloadAudioSettings() {
2895        IAudioService service = getService();
2896        try {
2897            service.reloadAudioSettings();
2898        } catch (RemoteException e) {
2899            Log.e(TAG, "Dead object in reloadAudioSettings"+e);
2900        }
2901    }
2902
2903    /**
2904     * @hide
2905     * Notifies AudioService that it is connected to an A2DP device that supports absolute volume,
2906     * so that AudioService can send volume change events to the A2DP device, rather than handling
2907     * them.
2908     */
2909    public void avrcpSupportsAbsoluteVolume(String address, boolean support) {
2910        IAudioService service = getService();
2911        try {
2912            service.avrcpSupportsAbsoluteVolume(address, support);
2913        } catch (RemoteException e) {
2914            Log.e(TAG, "Dead object in avrcpSupportsAbsoluteVolume", e);
2915        }
2916    }
2917
2918     /**
2919      * {@hide}
2920      */
2921     private final IBinder mICallBack = new Binder();
2922
2923    /**
2924     * Checks whether the phone is in silent mode, with or without vibrate.
2925     *
2926     * @return true if phone is in silent mode, with or without vibrate.
2927     *
2928     * @see #getRingerMode()
2929     *
2930     * @hide pending API Council approval
2931     */
2932    public boolean isSilentMode() {
2933        int ringerMode = getRingerMode();
2934        boolean silentMode =
2935            (ringerMode == RINGER_MODE_SILENT) ||
2936            (ringerMode == RINGER_MODE_VIBRATE);
2937        return silentMode;
2938    }
2939
2940    // This section re-defines new output device constants from AudioSystem, because the AudioSystem
2941    // class is not used by other parts of the framework, which instead use definitions and methods
2942    // from AudioManager. AudioSystem is an internal class used by AudioManager and AudioService.
2943
2944    /** @hide
2945     * The audio device code for representing "no device." */
2946    public static final int DEVICE_NONE = AudioSystem.DEVICE_NONE;
2947    /** @hide
2948     *  The audio output device code for the small speaker at the front of the device used
2949     *  when placing calls.  Does not refer to an in-ear headphone without attached microphone,
2950     *  such as earbuds, earphones, or in-ear monitors (IEM). Those would be handled as a
2951     *  {@link #DEVICE_OUT_WIRED_HEADPHONE}.
2952     */
2953    public static final int DEVICE_OUT_EARPIECE = AudioSystem.DEVICE_OUT_EARPIECE;
2954    /** @hide
2955     *  The audio output device code for the built-in speaker */
2956    public static final int DEVICE_OUT_SPEAKER = AudioSystem.DEVICE_OUT_SPEAKER;
2957    /** @hide
2958     * The audio output device code for a wired headset with attached microphone */
2959    public static final int DEVICE_OUT_WIRED_HEADSET = AudioSystem.DEVICE_OUT_WIRED_HEADSET;
2960    /** @hide
2961     * The audio output device code for a wired headphone without attached microphone */
2962    public static final int DEVICE_OUT_WIRED_HEADPHONE = AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
2963    /** @hide
2964     * The audio output device code for generic Bluetooth SCO, for voice */
2965    public static final int DEVICE_OUT_BLUETOOTH_SCO = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
2966    /** @hide
2967     * The audio output device code for Bluetooth SCO Headset Profile (HSP) and
2968     * Hands-Free Profile (HFP), for voice
2969     */
2970    public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET =
2971            AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2972    /** @hide
2973     * The audio output device code for Bluetooth SCO car audio, for voice */
2974    public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT =
2975            AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2976    /** @hide
2977     * The audio output device code for generic Bluetooth A2DP, for music */
2978    public static final int DEVICE_OUT_BLUETOOTH_A2DP = AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP;
2979    /** @hide
2980     * The audio output device code for Bluetooth A2DP headphones, for music */
2981    public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES =
2982            AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2983    /** @hide
2984     * The audio output device code for Bluetooth A2DP external speaker, for music */
2985    public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER =
2986            AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2987    /** @hide
2988     * The audio output device code for S/PDIF (legacy) or HDMI
2989     * Deprecated: replaced by {@link #DEVICE_OUT_HDMI} */
2990    public static final int DEVICE_OUT_AUX_DIGITAL = AudioSystem.DEVICE_OUT_AUX_DIGITAL;
2991    /** @hide
2992     * The audio output device code for HDMI */
2993    public static final int DEVICE_OUT_HDMI = AudioSystem.DEVICE_OUT_HDMI;
2994    /** @hide
2995     * The audio output device code for an analog wired headset attached via a
2996     *  docking station
2997     */
2998    public static final int DEVICE_OUT_ANLG_DOCK_HEADSET = AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
2999    /** @hide
3000     * The audio output device code for a digital wired headset attached via a
3001     *  docking station
3002     */
3003    public static final int DEVICE_OUT_DGTL_DOCK_HEADSET = AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET;
3004    /** @hide
3005     * The audio output device code for a USB audio accessory. The accessory is in USB host
3006     * mode and the Android device in USB device mode
3007     */
3008    public static final int DEVICE_OUT_USB_ACCESSORY = AudioSystem.DEVICE_OUT_USB_ACCESSORY;
3009    /** @hide
3010     * The audio output device code for a USB audio device. The device is in USB device
3011     * mode and the Android device in USB host mode
3012     */
3013    public static final int DEVICE_OUT_USB_DEVICE = AudioSystem.DEVICE_OUT_USB_DEVICE;
3014    /** @hide
3015     * The audio output device code for projection output.
3016     */
3017    public static final int DEVICE_OUT_REMOTE_SUBMIX = AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
3018    /** @hide
3019     * The audio output device code the telephony voice TX path.
3020     */
3021    public static final int DEVICE_OUT_TELEPHONY_TX = AudioSystem.DEVICE_OUT_TELEPHONY_TX;
3022    /** @hide
3023     * The audio output device code for an analog jack with line impedance detected.
3024     */
3025    public static final int DEVICE_OUT_LINE = AudioSystem.DEVICE_OUT_LINE;
3026    /** @hide
3027     * The audio output device code for HDMI Audio Return Channel.
3028     */
3029    public static final int DEVICE_OUT_HDMI_ARC = AudioSystem.DEVICE_OUT_HDMI_ARC;
3030    /** @hide
3031     * The audio output device code for S/PDIF digital connection.
3032     */
3033    public static final int DEVICE_OUT_SPDIF = AudioSystem.DEVICE_OUT_SPDIF;
3034    /** @hide
3035     * The audio output device code for built-in FM transmitter.
3036     */
3037    public static final int DEVICE_OUT_FM = AudioSystem.DEVICE_OUT_FM;
3038    /** @hide
3039     * This is not used as a returned value from {@link #getDevicesForStream}, but could be
3040     *  used in the future in a set method to select whatever default device is chosen by the
3041     *  platform-specific implementation.
3042     */
3043    public static final int DEVICE_OUT_DEFAULT = AudioSystem.DEVICE_OUT_DEFAULT;
3044
3045    /** @hide
3046     * The audio input device code for default built-in microphone
3047     */
3048    public static final int DEVICE_IN_BUILTIN_MIC = AudioSystem.DEVICE_IN_BUILTIN_MIC;
3049    /** @hide
3050     * The audio input device code for a Bluetooth SCO headset
3051     */
3052    public static final int DEVICE_IN_BLUETOOTH_SCO_HEADSET =
3053                                    AudioSystem.DEVICE_IN_BLUETOOTH_SCO_HEADSET;
3054    /** @hide
3055     * The audio input device code for wired headset microphone
3056     */
3057    public static final int DEVICE_IN_WIRED_HEADSET =
3058                                    AudioSystem.DEVICE_IN_WIRED_HEADSET;
3059    /** @hide
3060     * The audio input device code for HDMI
3061     */
3062    public static final int DEVICE_IN_HDMI =
3063                                    AudioSystem.DEVICE_IN_HDMI;
3064    /** @hide
3065     * The audio input device code for telephony voice RX path
3066     */
3067    public static final int DEVICE_IN_TELEPHONY_RX =
3068                                    AudioSystem.DEVICE_IN_TELEPHONY_RX;
3069    /** @hide
3070     * The audio input device code for built-in microphone pointing to the back
3071     */
3072    public static final int DEVICE_IN_BACK_MIC =
3073                                    AudioSystem.DEVICE_IN_BACK_MIC;
3074    /** @hide
3075     * The audio input device code for analog from a docking station
3076     */
3077    public static final int DEVICE_IN_ANLG_DOCK_HEADSET =
3078                                    AudioSystem.DEVICE_IN_ANLG_DOCK_HEADSET;
3079    /** @hide
3080     * The audio input device code for digital from a docking station
3081     */
3082    public static final int DEVICE_IN_DGTL_DOCK_HEADSET =
3083                                    AudioSystem.DEVICE_IN_DGTL_DOCK_HEADSET;
3084    /** @hide
3085     * The audio input device code for a USB audio accessory. The accessory is in USB host
3086     * mode and the Android device in USB device mode
3087     */
3088    public static final int DEVICE_IN_USB_ACCESSORY =
3089                                    AudioSystem.DEVICE_IN_USB_ACCESSORY;
3090    /** @hide
3091     * The audio input device code for a USB audio device. The device is in USB device
3092     * mode and the Android device in USB host mode
3093     */
3094    public static final int DEVICE_IN_USB_DEVICE =
3095                                    AudioSystem.DEVICE_IN_USB_DEVICE;
3096    /** @hide
3097     * The audio input device code for a FM radio tuner
3098     */
3099    public static final int DEVICE_IN_FM_TUNER = AudioSystem.DEVICE_IN_FM_TUNER;
3100    /** @hide
3101     * The audio input device code for a TV tuner
3102     */
3103    public static final int DEVICE_IN_TV_TUNER = AudioSystem.DEVICE_IN_TV_TUNER;
3104    /** @hide
3105     * The audio input device code for an analog jack with line impedance detected
3106     */
3107    public static final int DEVICE_IN_LINE = AudioSystem.DEVICE_IN_LINE;
3108    /** @hide
3109     * The audio input device code for a S/PDIF digital connection
3110     */
3111    public static final int DEVICE_IN_SPDIF = AudioSystem.DEVICE_IN_SPDIF;
3112    /** @hide
3113     * The audio input device code for audio loopback
3114     */
3115    public static final int DEVICE_IN_LOOPBACK = AudioSystem.DEVICE_IN_LOOPBACK;
3116
3117    /**
3118     * Return true if the device code corresponds to an output device.
3119     * @hide
3120     */
3121    public static boolean isOutputDevice(int device)
3122    {
3123        return (device & AudioSystem.DEVICE_BIT_IN) == 0;
3124    }
3125
3126    /**
3127     * Return true if the device code corresponds to an input device.
3128     * @hide
3129     */
3130    public static boolean isInputDevice(int device)
3131    {
3132        return (device & AudioSystem.DEVICE_BIT_IN) == AudioSystem.DEVICE_BIT_IN;
3133    }
3134
3135
3136    /**
3137     * Return the enabled devices for the specified output stream type.
3138     *
3139     * @param streamType The stream type to query. One of
3140     *            {@link #STREAM_VOICE_CALL},
3141     *            {@link #STREAM_SYSTEM},
3142     *            {@link #STREAM_RING},
3143     *            {@link #STREAM_MUSIC},
3144     *            {@link #STREAM_ALARM},
3145     *            {@link #STREAM_NOTIFICATION},
3146     *            {@link #STREAM_DTMF}.
3147     *
3148     * @return The bit-mask "or" of audio output device codes for all enabled devices on this
3149     *         stream. Zero or more of
3150     *            {@link #DEVICE_OUT_EARPIECE},
3151     *            {@link #DEVICE_OUT_SPEAKER},
3152     *            {@link #DEVICE_OUT_WIRED_HEADSET},
3153     *            {@link #DEVICE_OUT_WIRED_HEADPHONE},
3154     *            {@link #DEVICE_OUT_BLUETOOTH_SCO},
3155     *            {@link #DEVICE_OUT_BLUETOOTH_SCO_HEADSET},
3156     *            {@link #DEVICE_OUT_BLUETOOTH_SCO_CARKIT},
3157     *            {@link #DEVICE_OUT_BLUETOOTH_A2DP},
3158     *            {@link #DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES},
3159     *            {@link #DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER},
3160     *            {@link #DEVICE_OUT_HDMI},
3161     *            {@link #DEVICE_OUT_ANLG_DOCK_HEADSET},
3162     *            {@link #DEVICE_OUT_DGTL_DOCK_HEADSET}.
3163     *            {@link #DEVICE_OUT_USB_ACCESSORY}.
3164     *            {@link #DEVICE_OUT_USB_DEVICE}.
3165     *            {@link #DEVICE_OUT_REMOTE_SUBMIX}.
3166     *            {@link #DEVICE_OUT_TELEPHONY_TX}.
3167     *            {@link #DEVICE_OUT_LINE}.
3168     *            {@link #DEVICE_OUT_HDMI_ARC}.
3169     *            {@link #DEVICE_OUT_SPDIF}.
3170     *            {@link #DEVICE_OUT_FM}.
3171     *            {@link #DEVICE_OUT_DEFAULT} is not used here.
3172     *
3173     * The implementation may support additional device codes beyond those listed, so
3174     * the application should ignore any bits which it does not recognize.
3175     * Note that the information may be imprecise when the implementation
3176     * cannot distinguish whether a particular device is enabled.
3177     *
3178     * {@hide}
3179     */
3180    public int getDevicesForStream(int streamType) {
3181        switch (streamType) {
3182        case STREAM_VOICE_CALL:
3183        case STREAM_SYSTEM:
3184        case STREAM_RING:
3185        case STREAM_MUSIC:
3186        case STREAM_ALARM:
3187        case STREAM_NOTIFICATION:
3188        case STREAM_DTMF:
3189            return AudioSystem.getDevicesForStream(streamType);
3190        default:
3191            return 0;
3192        }
3193    }
3194
3195     /**
3196     * Indicate wired accessory connection state change.
3197     * @param device type of device connected/disconnected (AudioManager.DEVICE_OUT_xxx)
3198     * @param state  new connection state: 1 connected, 0 disconnected
3199     * @param name   device name
3200     * {@hide}
3201     */
3202    public void setWiredDeviceConnectionState(int type, int state, String address, String name) {
3203        IAudioService service = getService();
3204        try {
3205            service.setWiredDeviceConnectionState(type, state, address, name);
3206        } catch (RemoteException e) {
3207            Log.e(TAG, "Dead object in setWiredDeviceConnectionState "+e);
3208        }
3209    }
3210
3211     /**
3212     * Indicate A2DP source or sink connection state change.
3213     * @param device Bluetooth device connected/disconnected
3214     * @param state  new connection state (BluetoothProfile.STATE_xxx)
3215     * @param profile profile for the A2DP device
3216     * (either {@link android.bluetooth.BluetoothProfile.A2DP} or
3217     * {@link android.bluetooth.BluetoothProfile.A2DP_SINK})
3218     * @return a delay in ms that the caller should wait before broadcasting
3219     * BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED intent.
3220     * {@hide}
3221     */
3222    public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state,
3223            int profile) {
3224        IAudioService service = getService();
3225        int delay = 0;
3226        try {
3227            delay = service.setBluetoothA2dpDeviceConnectionState(device, state, profile);
3228        } catch (RemoteException e) {
3229            Log.e(TAG, "Dead object in setBluetoothA2dpDeviceConnectionState "+e);
3230        } finally {
3231            return delay;
3232        }
3233    }
3234
3235    /** {@hide} */
3236    public IRingtonePlayer getRingtonePlayer() {
3237        try {
3238            return getService().getRingtonePlayer();
3239        } catch (RemoteException e) {
3240            return null;
3241        }
3242    }
3243
3244    /**
3245     * Used as a key for {@link #getProperty} to request the native or optimal output sample rate
3246     * for this device's primary output stream, in decimal Hz.
3247     */
3248    public static final String PROPERTY_OUTPUT_SAMPLE_RATE =
3249            "android.media.property.OUTPUT_SAMPLE_RATE";
3250
3251    /**
3252     * Used as a key for {@link #getProperty} to request the native or optimal output buffer size
3253     * for this device's primary output stream, in decimal PCM frames.
3254     */
3255    public static final String PROPERTY_OUTPUT_FRAMES_PER_BUFFER =
3256            "android.media.property.OUTPUT_FRAMES_PER_BUFFER";
3257
3258    /**
3259     * Returns the value of the property with the specified key.
3260     * @param key One of the strings corresponding to a property key: either
3261     *            {@link #PROPERTY_OUTPUT_SAMPLE_RATE} or
3262     *            {@link #PROPERTY_OUTPUT_FRAMES_PER_BUFFER}
3263     * @return A string representing the associated value for that property key,
3264     *         or null if there is no value for that key.
3265     */
3266    public String getProperty(String key) {
3267        if (PROPERTY_OUTPUT_SAMPLE_RATE.equals(key)) {
3268            int outputSampleRate = AudioSystem.getPrimaryOutputSamplingRate();
3269            return outputSampleRate > 0 ? Integer.toString(outputSampleRate) : null;
3270        } else if (PROPERTY_OUTPUT_FRAMES_PER_BUFFER.equals(key)) {
3271            int outputFramesPerBuffer = AudioSystem.getPrimaryOutputFrameCount();
3272            return outputFramesPerBuffer > 0 ? Integer.toString(outputFramesPerBuffer) : null;
3273        } else {
3274            // null or unknown key
3275            return null;
3276        }
3277    }
3278
3279    /**
3280     * Returns the estimated latency for the given stream type in milliseconds.
3281     *
3282     * DO NOT UNHIDE. The existing approach for doing A/V sync has too many problems. We need
3283     * a better solution.
3284     * @hide
3285     */
3286    public int getOutputLatency(int streamType) {
3287        return AudioSystem.getOutputLatency(streamType);
3288    }
3289
3290    /**
3291     * Registers a global volume controller interface.  Currently limited to SystemUI.
3292     *
3293     * @hide
3294     */
3295    public void setVolumeController(IVolumeController controller) {
3296        try {
3297            getService().setVolumeController(controller);
3298        } catch (RemoteException e) {
3299            Log.w(TAG, "Error setting volume controller", e);
3300        }
3301    }
3302
3303    /**
3304     * Notify audio manager about volume controller visibility changes.
3305     * Currently limited to SystemUI.
3306     *
3307     * @hide
3308     */
3309    public void notifyVolumeControllerVisible(IVolumeController controller, boolean visible) {
3310        try {
3311            getService().notifyVolumeControllerVisible(controller, visible);
3312        } catch (RemoteException e) {
3313            Log.w(TAG, "Error notifying about volume controller visibility", e);
3314        }
3315    }
3316
3317    /**
3318     * Only useful for volume controllers.
3319     * @hide
3320     */
3321    public boolean isStreamAffectedByRingerMode(int streamType) {
3322        try {
3323            return getService().isStreamAffectedByRingerMode(streamType);
3324        } catch (RemoteException e) {
3325            Log.w(TAG, "Error calling isStreamAffectedByRingerMode", e);
3326            return false;
3327        }
3328    }
3329
3330    /**
3331     * Only useful for volume controllers.
3332     * @hide
3333     */
3334    public void disableSafeMediaVolume() {
3335        try {
3336            getService().disableSafeMediaVolume();
3337        } catch (RemoteException e) {
3338            Log.w(TAG, "Error disabling safe media volume", e);
3339        }
3340    }
3341
3342    /**
3343     * Only useful for volume controllers.
3344     * @hide
3345     */
3346    public void setRingerModeInternal(int ringerMode) {
3347        try {
3348            getService().setRingerModeInternal(ringerMode, mContext.getOpPackageName());
3349        } catch (RemoteException e) {
3350            Log.w(TAG, "Error calling setRingerModeInternal", e);
3351        }
3352    }
3353
3354    /**
3355     * Only useful for volume controllers.
3356     * @hide
3357     */
3358    public int getRingerModeInternal() {
3359        try {
3360            return getService().getRingerModeInternal();
3361        } catch (RemoteException e) {
3362            Log.w(TAG, "Error calling getRingerModeInternal", e);
3363            return RINGER_MODE_NORMAL;
3364        }
3365    }
3366
3367    /**
3368     * Set Hdmi Cec system audio mode.
3369     *
3370     * @param on whether to be on system audio mode
3371     * @return output device type. 0 (DEVICE_NONE) if failed to set device.
3372     * @hide
3373     */
3374    public int setHdmiSystemAudioSupported(boolean on) {
3375        try {
3376            return getService().setHdmiSystemAudioSupported(on);
3377        } catch (RemoteException e) {
3378            Log.w(TAG, "Error setting system audio mode", e);
3379            return AudioSystem.DEVICE_NONE;
3380        }
3381    }
3382
3383    /**
3384     * Returns true if Hdmi Cec system audio mode is supported.
3385     *
3386     * @hide
3387     */
3388    @SystemApi
3389    public boolean isHdmiSystemAudioSupported() {
3390        try {
3391            return getService().isHdmiSystemAudioSupported();
3392        } catch (RemoteException e) {
3393            Log.w(TAG, "Error querying system audio mode", e);
3394            return false;
3395        }
3396    }
3397
3398    /**
3399     * Return codes for listAudioPorts(), createAudioPatch() ...
3400     */
3401
3402    /** @hide
3403     * CANDIDATE FOR PUBLIC API
3404     */
3405    public static final int SUCCESS = AudioSystem.SUCCESS;
3406    /**
3407     * A default error code.
3408     */
3409    public static final int ERROR = AudioSystem.ERROR;
3410    /** @hide
3411     * CANDIDATE FOR PUBLIC API
3412     */
3413    public static final int ERROR_BAD_VALUE = AudioSystem.BAD_VALUE;
3414    /** @hide
3415     */
3416    public static final int ERROR_INVALID_OPERATION = AudioSystem.INVALID_OPERATION;
3417    /** @hide
3418     */
3419    public static final int ERROR_PERMISSION_DENIED = AudioSystem.PERMISSION_DENIED;
3420    /** @hide
3421     */
3422    public static final int ERROR_NO_INIT = AudioSystem.NO_INIT;
3423    /**
3424     * An error code indicating that the object reporting it is no longer valid and needs to
3425     * be recreated.
3426     */
3427    public static final int ERROR_DEAD_OBJECT = AudioSystem.DEAD_OBJECT;
3428
3429    /**
3430     * Returns a list of descriptors for all audio ports managed by the audio framework.
3431     * Audio ports are nodes in the audio framework or audio hardware that can be configured
3432     * or connected and disconnected with createAudioPatch() or releaseAudioPatch().
3433     * See AudioPort for a list of attributes of each audio port.
3434     * @param ports An AudioPort ArrayList where the list will be returned.
3435     * @hide
3436     */
3437    public int listAudioPorts(ArrayList<AudioPort> ports) {
3438        return updateAudioPortCache(ports, null);
3439    }
3440
3441    /**
3442     * Specialized version of listAudioPorts() listing only audio devices (AudioDevicePort)
3443     * @see listAudioPorts(ArrayList<AudioPort>)
3444     * @hide
3445     */
3446    public int listAudioDevicePorts(ArrayList<AudioPort> devices) {
3447        ArrayList<AudioPort> ports = new ArrayList<AudioPort>();
3448        int status = updateAudioPortCache(ports, null);
3449        if (status == SUCCESS) {
3450            devices.clear();
3451            for (int i = 0; i < ports.size(); i++) {
3452                if (ports.get(i) instanceof AudioDevicePort) {
3453                    devices.add(ports.get(i));
3454                }
3455            }
3456        }
3457        return status;
3458    }
3459
3460    /**
3461     * Create a connection between two or more devices. The framework will reject the request if
3462     * device types are not compatible or the implementation does not support the requested
3463     * configuration.
3464     * NOTE: current implementation is limited to one source and one sink per patch.
3465     * @param patch AudioPatch array where the newly created patch will be returned.
3466     *              As input, if patch[0] is not null, the specified patch will be replaced by the
3467     *              new patch created. This avoids calling releaseAudioPatch() when modifying a
3468     *              patch and allows the implementation to optimize transitions.
3469     * @param sources List of source audio ports. All must be AudioPort.ROLE_SOURCE.
3470     * @param sinks   List of sink audio ports. All must be AudioPort.ROLE_SINK.
3471     *
3472     * @return - {@link #SUCCESS} if connection is successful.
3473     *         - {@link #ERROR_BAD_VALUE} if incompatible device types are passed.
3474     *         - {@link #ERROR_INVALID_OPERATION} if the requested connection is not supported.
3475     *         - {@link #ERROR_PERMISSION_DENIED} if the client does not have permission to create
3476     *         a patch.
3477     *         - {@link #ERROR_DEAD_OBJECT} if the server process is dead
3478     *         - {@link #ERROR} if patch cannot be connected for any other reason.
3479     *
3480     *         patch[0] contains the newly created patch
3481     * @hide
3482     */
3483    public int createAudioPatch(AudioPatch[] patch,
3484                                 AudioPortConfig[] sources,
3485                                 AudioPortConfig[] sinks) {
3486        return AudioSystem.createAudioPatch(patch, sources, sinks);
3487    }
3488
3489    /**
3490     * Releases an existing audio patch connection.
3491     * @param patch The audio patch to disconnect.
3492     * @return - {@link #SUCCESS} if disconnection is successful.
3493     *         - {@link #ERROR_BAD_VALUE} if the specified patch does not exist.
3494     *         - {@link #ERROR_PERMISSION_DENIED} if the client does not have permission to release
3495     *         a patch.
3496     *         - {@link #ERROR_DEAD_OBJECT} if the server process is dead
3497     *         - {@link #ERROR} if patch cannot be released for any other reason.
3498     * @hide
3499     */
3500    public int releaseAudioPatch(AudioPatch patch) {
3501        return AudioSystem.releaseAudioPatch(patch);
3502    }
3503
3504    /**
3505     * List all existing connections between audio ports.
3506     * @param patches An AudioPatch array where the list will be returned.
3507     * @hide
3508     */
3509    public int listAudioPatches(ArrayList<AudioPatch> patches) {
3510        return updateAudioPortCache(null, patches);
3511    }
3512
3513    /**
3514     * Set the gain on the specified AudioPort. The AudioGainConfig config is build by
3515     * AudioGain.buildConfig()
3516     * @hide
3517     */
3518    public int setAudioPortGain(AudioPort port, AudioGainConfig gain) {
3519        if (port == null || gain == null) {
3520            return ERROR_BAD_VALUE;
3521        }
3522        AudioPortConfig activeConfig = port.activeConfig();
3523        AudioPortConfig config = new AudioPortConfig(port, activeConfig.samplingRate(),
3524                                        activeConfig.channelMask(), activeConfig.format(), gain);
3525        config.mConfigMask = AudioPortConfig.GAIN;
3526        return AudioSystem.setAudioPortConfig(config);
3527    }
3528
3529    /**
3530     * Listener registered by client to be notified upon new audio port connections,
3531     * disconnections or attributes update.
3532     * @hide
3533     */
3534    public interface OnAudioPortUpdateListener {
3535        /**
3536         * Callback method called upon audio port list update.
3537         * @param portList the updated list of audio ports
3538         */
3539        public void onAudioPortListUpdate(AudioPort[] portList);
3540
3541        /**
3542         * Callback method called upon audio patch list update.
3543         * @param patchList the updated list of audio patches
3544         */
3545        public void onAudioPatchListUpdate(AudioPatch[] patchList);
3546
3547        /**
3548         * Callback method called when the mediaserver dies
3549         */
3550        public void onServiceDied();
3551    }
3552
3553    /**
3554     * Register an audio port list update listener.
3555     * @hide
3556     */
3557    public void registerAudioPortUpdateListener(OnAudioPortUpdateListener l) {
3558        sAudioPortEventHandler.registerListener(l);
3559    }
3560
3561    /**
3562     * Unregister an audio port list update listener.
3563     * @hide
3564     */
3565    public void unregisterAudioPortUpdateListener(OnAudioPortUpdateListener l) {
3566        sAudioPortEventHandler.unregisterListener(l);
3567    }
3568
3569    //
3570    // AudioPort implementation
3571    //
3572
3573    static final int AUDIOPORT_GENERATION_INIT = 0;
3574    static Integer sAudioPortGeneration = new Integer(AUDIOPORT_GENERATION_INIT);
3575    static ArrayList<AudioPort> sAudioPortsCached = new ArrayList<AudioPort>();
3576    static ArrayList<AudioPatch> sAudioPatchesCached = new ArrayList<AudioPatch>();
3577
3578    static int resetAudioPortGeneration() {
3579        int generation;
3580        synchronized (sAudioPortGeneration) {
3581            generation = sAudioPortGeneration;
3582            sAudioPortGeneration = AUDIOPORT_GENERATION_INIT;
3583        }
3584        return generation;
3585    }
3586
3587    static int updateAudioPortCache(ArrayList<AudioPort> ports, ArrayList<AudioPatch> patches) {
3588        synchronized (sAudioPortGeneration) {
3589
3590            if (sAudioPortGeneration == AUDIOPORT_GENERATION_INIT) {
3591                int[] patchGeneration = new int[1];
3592                int[] portGeneration = new int[1];
3593                int status;
3594                ArrayList<AudioPort> newPorts = new ArrayList<AudioPort>();
3595                ArrayList<AudioPatch> newPatches = new ArrayList<AudioPatch>();
3596
3597                do {
3598                    newPorts.clear();
3599                    status = AudioSystem.listAudioPorts(newPorts, portGeneration);
3600                    if (status != SUCCESS) {
3601                        Log.w(TAG, "updateAudioPortCache: listAudioPorts failed");
3602                        return status;
3603                    }
3604                    newPatches.clear();
3605                    status = AudioSystem.listAudioPatches(newPatches, patchGeneration);
3606                    if (status != SUCCESS) {
3607                        Log.w(TAG, "updateAudioPortCache: listAudioPatches failed");
3608                        return status;
3609                    }
3610                } while (patchGeneration[0] != portGeneration[0]);
3611
3612                for (int i = 0; i < newPatches.size(); i++) {
3613                    for (int j = 0; j < newPatches.get(i).sources().length; j++) {
3614                        AudioPortConfig portCfg = updatePortConfig(newPatches.get(i).sources()[j],
3615                                                                   newPorts);
3616                        newPatches.get(i).sources()[j] = portCfg;
3617                    }
3618                    for (int j = 0; j < newPatches.get(i).sinks().length; j++) {
3619                        AudioPortConfig portCfg = updatePortConfig(newPatches.get(i).sinks()[j],
3620                                                                   newPorts);
3621                        newPatches.get(i).sinks()[j] = portCfg;
3622                    }
3623                }
3624                for (Iterator<AudioPatch> i = newPatches.iterator(); i.hasNext(); ) {
3625                    AudioPatch newPatch = i.next();
3626                    boolean hasInvalidPort = false;
3627                    for (AudioPortConfig portCfg : newPatch.sources()) {
3628                        if (portCfg == null) {
3629                            hasInvalidPort = true;
3630                            break;
3631                        }
3632                    }
3633                    for (AudioPortConfig portCfg : newPatch.sinks()) {
3634                        if (portCfg == null) {
3635                            hasInvalidPort = true;
3636                            break;
3637                        }
3638                    }
3639                    if (hasInvalidPort) {
3640                        // Temporarily remove patches with invalid ports. One who created the patch
3641                        // is responsible for dealing with the port change.
3642                        i.remove();
3643                    }
3644                }
3645
3646                sAudioPortsCached = newPorts;
3647                sAudioPatchesCached = newPatches;
3648                sAudioPortGeneration = portGeneration[0];
3649            }
3650            if (ports != null) {
3651                ports.clear();
3652                ports.addAll(sAudioPortsCached);
3653            }
3654            if (patches != null) {
3655                patches.clear();
3656                patches.addAll(sAudioPatchesCached);
3657            }
3658        }
3659        return SUCCESS;
3660    }
3661
3662    static AudioPortConfig updatePortConfig(AudioPortConfig portCfg, ArrayList<AudioPort> ports) {
3663        AudioPort port = portCfg.port();
3664        int k;
3665        for (k = 0; k < ports.size(); k++) {
3666            // compare handles because the port returned by JNI is not of the correct
3667            // subclass
3668            if (ports.get(k).handle().equals(port.handle())) {
3669                port = ports.get(k);
3670                break;
3671            }
3672        }
3673        if (k == ports.size()) {
3674            // this hould never happen
3675            Log.e(TAG, "updatePortConfig port not found for handle: "+port.handle().id());
3676            return null;
3677        }
3678        AudioGainConfig gainCfg = portCfg.gain();
3679        if (gainCfg != null) {
3680            AudioGain gain = port.gain(gainCfg.index());
3681            gainCfg = gain.buildConfig(gainCfg.mode(),
3682                                       gainCfg.channelMask(),
3683                                       gainCfg.values(),
3684                                       gainCfg.rampDurationMs());
3685        }
3686        return port.buildConfig(portCfg.samplingRate(),
3687                                                 portCfg.channelMask(),
3688                                                 portCfg.format(),
3689                                                 gainCfg);
3690    }
3691}
3692