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