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