OSDN Git Service

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