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