2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.media;
19 import android.Manifest;
20 import android.annotation.NonNull;
21 import android.annotation.SdkConstant;
22 import android.annotation.SdkConstant.SdkConstantType;
23 import android.annotation.SystemApi;
24 import android.app.PendingIntent;
25 import android.bluetooth.BluetoothDevice;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.media.audiopolicy.AudioPolicy;
30 import android.media.session.MediaController;
31 import android.media.session.MediaSession;
32 import android.media.session.MediaSessionLegacyHelper;
33 import android.media.session.MediaSessionManager;
34 import android.os.Binder;
35 import android.os.Handler;
36 import android.os.IBinder;
37 import android.os.Looper;
38 import android.os.Message;
39 import android.os.Process;
40 import android.os.RemoteException;
41 import android.os.SystemProperties;
42 import android.os.SystemClock;
43 import android.os.ServiceManager;
44 import android.provider.Settings;
45 import android.util.Log;
46 import android.view.KeyEvent;
48 import java.util.ArrayList;
49 import java.util.HashMap;
50 import java.util.Iterator;
53 * AudioManager provides access to volume and ringer mode control.
55 * Use <code>Context.getSystemService(Context.AUDIO_SERVICE)</code> to get
56 * an instance of this class.
58 public class AudioManager {
60 private Context mOriginalContext;
61 private Context mApplicationContext;
62 private long mVolumeKeyUpTime;
63 private final boolean mUseVolumeKeySounds;
64 private final boolean mUseFixedVolume;
65 private static String TAG = "AudioManager";
66 private static final AudioPortEventHandler sAudioPortEventHandler = new AudioPortEventHandler();
69 * System properties for whether the default microphone and speaker paths support
70 * near-ultrasound frequencies (range of 18 - 21 kHz).
72 private static final String SYSTEM_PROPERTY_MIC_NEAR_ULTRASOUND =
73 "persist.audio.mic.ultrasound";
74 private static final String SYSTEM_PROPERTY_SPEAKER_NEAR_ULTRASOUND =
75 "persist.audio.spkr.ultrasound";
76 private static final String DEFAULT_RESULT_FALSE_STRING = "false";
79 * Broadcast intent, a hint for applications that audio is about to become
80 * 'noisy' due to a change in audio outputs. For example, this intent may
81 * be sent when a wired headset is unplugged, or when an A2DP audio
82 * sink is disconnected, and the audio system is about to automatically
83 * switch audio route to the speaker. Applications that are controlling
84 * audio streams may consider pausing, reducing volume or some other action
85 * on receipt of this intent so as not to surprise the user with audio
88 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
89 public static final String ACTION_AUDIO_BECOMING_NOISY = "android.media.AUDIO_BECOMING_NOISY";
92 * Sticky broadcast intent action indicating that the ringer mode has
93 * changed. Includes the new ringer mode.
95 * @see #EXTRA_RINGER_MODE
97 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
98 public static final String RINGER_MODE_CHANGED_ACTION = "android.media.RINGER_MODE_CHANGED";
102 * Sticky broadcast intent action indicating that the internal ringer mode has
103 * changed. Includes the new ringer mode.
105 * @see #EXTRA_RINGER_MODE
107 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
108 public static final String INTERNAL_RINGER_MODE_CHANGED_ACTION =
109 "android.media.INTERNAL_RINGER_MODE_CHANGED_ACTION";
112 * The new ringer mode.
114 * @see #RINGER_MODE_CHANGED_ACTION
115 * @see #RINGER_MODE_NORMAL
116 * @see #RINGER_MODE_SILENT
117 * @see #RINGER_MODE_VIBRATE
119 public static final String EXTRA_RINGER_MODE = "android.media.EXTRA_RINGER_MODE";
122 * Broadcast intent action indicating that the vibrate setting has
123 * changed. Includes the vibrate type and its new setting.
125 * @see #EXTRA_VIBRATE_TYPE
126 * @see #EXTRA_VIBRATE_SETTING
127 * @deprecated Applications should maintain their own vibrate policy based on
128 * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
130 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
131 public static final String VIBRATE_SETTING_CHANGED_ACTION =
132 "android.media.VIBRATE_SETTING_CHANGED";
135 * @hide Broadcast intent when the volume for a particular stream type changes.
136 * Includes the stream, the new volume and previous volumes.
138 * - for internal platform use only, do not make public,
139 * - never used for "remote" volume changes
141 * @see #EXTRA_VOLUME_STREAM_TYPE
142 * @see #EXTRA_VOLUME_STREAM_VALUE
143 * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
145 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
146 public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";
149 * @hide Broadcast intent when the devices for a particular stream type changes.
150 * Includes the stream, the new devices and previous devices.
152 * - for internal platform use only, do not make public,
153 * - never used for "remote" volume changes
155 * @see #EXTRA_VOLUME_STREAM_TYPE
156 * @see #EXTRA_VOLUME_STREAM_DEVICES
157 * @see #EXTRA_PREV_VOLUME_STREAM_DEVICES
158 * @see #getDevicesForStream
160 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
161 public static final String STREAM_DEVICES_CHANGED_ACTION =
162 "android.media.STREAM_DEVICES_CHANGED_ACTION";
165 * @hide Broadcast intent when a stream mute state changes.
166 * Includes the stream that changed and the new mute state
168 * @see #EXTRA_VOLUME_STREAM_TYPE
169 * @see #EXTRA_STREAM_VOLUME_MUTED
171 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
172 public static final String STREAM_MUTE_CHANGED_ACTION =
173 "android.media.STREAM_MUTE_CHANGED_ACTION";
176 * @hide Broadcast intent when the master mute state changes.
177 * Includes the the new volume
179 * @see #EXTRA_MASTER_VOLUME_MUTED
181 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
182 public static final String MASTER_MUTE_CHANGED_ACTION =
183 "android.media.MASTER_MUTE_CHANGED_ACTION";
186 * The new vibrate setting for a particular type.
188 * @see #VIBRATE_SETTING_CHANGED_ACTION
189 * @see #EXTRA_VIBRATE_TYPE
190 * @see #VIBRATE_SETTING_ON
191 * @see #VIBRATE_SETTING_OFF
192 * @see #VIBRATE_SETTING_ONLY_SILENT
193 * @deprecated Applications should maintain their own vibrate policy based on
194 * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
196 public static final String EXTRA_VIBRATE_SETTING = "android.media.EXTRA_VIBRATE_SETTING";
199 * The vibrate type whose setting has changed.
201 * @see #VIBRATE_SETTING_CHANGED_ACTION
202 * @see #VIBRATE_TYPE_NOTIFICATION
203 * @see #VIBRATE_TYPE_RINGER
204 * @deprecated Applications should maintain their own vibrate policy based on
205 * current ringer mode and listen to {@link #RINGER_MODE_CHANGED_ACTION} instead.
207 public static final String EXTRA_VIBRATE_TYPE = "android.media.EXTRA_VIBRATE_TYPE";
210 * @hide The stream type for the volume changed intent.
212 public static final String EXTRA_VOLUME_STREAM_TYPE = "android.media.EXTRA_VOLUME_STREAM_TYPE";
215 * @hide The volume associated with the stream for the volume changed intent.
217 public static final String EXTRA_VOLUME_STREAM_VALUE =
218 "android.media.EXTRA_VOLUME_STREAM_VALUE";
221 * @hide The previous volume associated with the stream for the volume changed intent.
223 public static final String EXTRA_PREV_VOLUME_STREAM_VALUE =
224 "android.media.EXTRA_PREV_VOLUME_STREAM_VALUE";
227 * @hide The devices associated with the stream for the stream devices changed intent.
229 public static final String EXTRA_VOLUME_STREAM_DEVICES =
230 "android.media.EXTRA_VOLUME_STREAM_DEVICES";
233 * @hide The previous devices associated with the stream for the stream devices changed intent.
235 public static final String EXTRA_PREV_VOLUME_STREAM_DEVICES =
236 "android.media.EXTRA_PREV_VOLUME_STREAM_DEVICES";
239 * @hide The new master volume mute state for the master mute changed intent.
242 public static final String EXTRA_MASTER_VOLUME_MUTED =
243 "android.media.EXTRA_MASTER_VOLUME_MUTED";
246 * @hide The new stream volume mute state for the stream mute changed intent.
249 public static final String EXTRA_STREAM_VOLUME_MUTED =
250 "android.media.EXTRA_STREAM_VOLUME_MUTED";
253 * Broadcast Action: Wired Headset plugged in or unplugged.
255 * You <em>cannot</em> receive this through components declared
256 * in manifests, only by explicitly registering for it with
257 * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)
258 * Context.registerReceiver()}.
260 * <p>The intent will have the following extra values:
262 * <li><em>state</em> - 0 for unplugged, 1 for plugged. </li>
263 * <li><em>name</em> - Headset type, human readable string </li>
264 * <li><em>microphone</em> - 1 if headset has a microphone, 0 otherwise </li>
268 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
269 public static final String ACTION_HEADSET_PLUG =
270 "android.intent.action.HEADSET_PLUG";
273 * Broadcast Action: A sticky broadcast indicating an HDMI cable was plugged or unplugged.
275 * The intent will have the following extra values: {@link #EXTRA_AUDIO_PLUG_STATE},
276 * {@link #EXTRA_MAX_CHANNEL_COUNT}, {@link #EXTRA_ENCODINGS}.
277 * <p>It can only be received by explicitly registering for it with
278 * {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)}.
280 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
281 public static final String ACTION_HDMI_AUDIO_PLUG =
282 "android.media.action.HDMI_AUDIO_PLUG";
285 * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to communicate whether HDMI is plugged in
287 * An integer value of 1 indicates a plugged-in state, 0 is unplugged.
289 public static final String EXTRA_AUDIO_PLUG_STATE = "android.media.extra.AUDIO_PLUG_STATE";
292 * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to define the maximum number of channels
293 * supported by the HDMI device.
294 * The corresponding integer value is only available when the device is plugged in (as expressed
295 * by {@link #EXTRA_AUDIO_PLUG_STATE}).
297 public static final String EXTRA_MAX_CHANNEL_COUNT = "android.media.extra.MAX_CHANNEL_COUNT";
300 * Extra used in {@link #ACTION_HDMI_AUDIO_PLUG} to define the audio encodings supported by
301 * the connected HDMI device.
302 * The corresponding array of encoding values is only available when the device is plugged in
303 * (as expressed by {@link #EXTRA_AUDIO_PLUG_STATE}). Encoding values are defined in
304 * {@link AudioFormat} (for instance see {@link AudioFormat#ENCODING_PCM_16BIT}). Use
305 * {@link android.content.Intent#getIntArrayExtra(String)} to retrieve the encoding values.
307 public static final String EXTRA_ENCODINGS = "android.media.extra.ENCODINGS";
309 /** The audio stream for phone calls */
310 public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
311 /** The audio stream for system sounds */
312 public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
313 /** The audio stream for the phone ring */
314 public static final int STREAM_RING = AudioSystem.STREAM_RING;
315 /** The audio stream for music playback */
316 public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
317 /** The audio stream for alarms */
318 public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
319 /** The audio stream for notifications */
320 public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
321 /** @hide The audio stream for phone calls when connected to bluetooth */
322 public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
323 /** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
324 public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
325 /** The audio stream for DTMF Tones */
326 public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
327 /** @hide The audio stream for text to speech (TTS) */
328 public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
329 /** Number of audio streams */
331 * @deprecated Use AudioSystem.getNumStreamTypes() instead
333 @Deprecated public static final int NUM_STREAMS = AudioSystem.NUM_STREAMS;
336 * Increase the ringer volume.
338 * @see #adjustVolume(int, int)
339 * @see #adjustStreamVolume(int, int, int)
341 public static final int ADJUST_RAISE = 1;
344 * Decrease the ringer volume.
346 * @see #adjustVolume(int, int)
347 * @see #adjustStreamVolume(int, int, int)
349 public static final int ADJUST_LOWER = -1;
352 * Maintain the previous ringer volume. This may be useful when needing to
353 * show the volume toast without actually modifying the volume.
355 * @see #adjustVolume(int, int)
356 * @see #adjustStreamVolume(int, int, int)
358 public static final int ADJUST_SAME = 0;
361 * Mute the volume. Has no effect if the stream is already muted.
363 * @see #adjustVolume(int, int)
364 * @see #adjustStreamVolume(int, int, int)
366 public static final int ADJUST_MUTE = -100;
369 * Unmute the volume. Has no effect if the stream is not muted.
371 * @see #adjustVolume(int, int)
372 * @see #adjustStreamVolume(int, int, int)
374 public static final int ADJUST_UNMUTE = 100;
377 * Toggle the mute state. If muted the stream will be unmuted. If not muted
378 * the stream will be muted.
380 * @see #adjustVolume(int, int)
381 * @see #adjustStreamVolume(int, int, int)
383 public static final int ADJUST_TOGGLE_MUTE = 101;
385 // Flags should be powers of 2!
388 * Show a toast containing the current volume.
390 * @see #adjustStreamVolume(int, int, int)
391 * @see #adjustVolume(int, int)
392 * @see #setStreamVolume(int, int, int)
393 * @see #setRingerMode(int)
395 public static final int FLAG_SHOW_UI = 1 << 0;
398 * Whether to include ringer modes as possible options when changing volume.
399 * For example, if true and volume level is 0 and the volume is adjusted
400 * with {@link #ADJUST_LOWER}, then the ringer mode may switch the silent or
403 * By default this is on for the ring stream. If this flag is included,
404 * this behavior will be present regardless of the stream type being
405 * affected by the ringer mode.
407 * @see #adjustVolume(int, int)
408 * @see #adjustStreamVolume(int, int, int)
410 public static final int FLAG_ALLOW_RINGER_MODES = 1 << 1;
413 * Whether to play a sound when changing the volume.
415 * If this is given to {@link #adjustVolume(int, int)} or
416 * {@link #adjustSuggestedStreamVolume(int, int, int)}, it may be ignored
417 * in some cases (for example, the decided stream type is not
418 * {@link AudioManager#STREAM_RING}, or the volume is being adjusted
421 * @see #adjustStreamVolume(int, int, int)
422 * @see #adjustVolume(int, int)
423 * @see #setStreamVolume(int, int, int)
425 public static final int FLAG_PLAY_SOUND = 1 << 2;
428 * Removes any sounds/vibrate that may be in the queue, or are playing (related to
431 public static final int FLAG_REMOVE_SOUND_AND_VIBRATE = 1 << 3;
434 * Whether to vibrate if going into the vibrate ringer mode.
436 public static final int FLAG_VIBRATE = 1 << 4;
439 * Indicates to VolumePanel that the volume slider should be disabled as user
440 * cannot change the stream volume
443 public static final int FLAG_FIXED_VOLUME = 1 << 5;
446 * Indicates the volume set/adjust call is for Bluetooth absolute volume
449 public static final int FLAG_BLUETOOTH_ABS_VOLUME = 1 << 6;
452 * Adjusting the volume was prevented due to silent mode, display a hint in the UI.
455 public static final int FLAG_SHOW_SILENT_HINT = 1 << 7;
458 * Indicates the volume call is for Hdmi Cec system audio volume
461 public static final int FLAG_HDMI_SYSTEM_AUDIO_VOLUME = 1 << 8;
464 * Indicates that this should only be handled if media is actively playing.
467 public static final int FLAG_ACTIVE_MEDIA_ONLY = 1 << 9;
470 * Like FLAG_SHOW_UI, but only dialog warnings and confirmations, no sliders.
473 public static final int FLAG_SHOW_UI_WARNINGS = 1 << 10;
476 * Adjusting the volume down from vibrated was prevented, display a hint in the UI.
479 public static final int FLAG_SHOW_VIBRATE_HINT = 1 << 11;
482 * Adjusting the volume due to a hardware key press.
485 public static final int FLAG_FROM_KEY = 1 << 12;
487 private static final String[] FLAG_NAMES = {
489 "FLAG_ALLOW_RINGER_MODES",
491 "FLAG_REMOVE_SOUND_AND_VIBRATE",
494 "FLAG_BLUETOOTH_ABS_VOLUME",
495 "FLAG_SHOW_SILENT_HINT",
496 "FLAG_HDMI_SYSTEM_AUDIO_VOLUME",
497 "FLAG_ACTIVE_MEDIA_ONLY",
498 "FLAG_SHOW_UI_WARNINGS",
499 "FLAG_SHOW_VIBRATE_HINT",
504 public static String flagsToString(int flags) {
505 final StringBuilder sb = new StringBuilder();
506 for (int i = 0; i < FLAG_NAMES.length; i++) {
507 final int flag = 1 << i;
508 if ((flags & flag) != 0) {
509 if (sb.length() > 0) {
512 sb.append(FLAG_NAMES[i]);
517 if (sb.length() > 0) {
522 return sb.toString();
526 * Ringer mode that will be silent and will not vibrate. (This overrides the
529 * @see #setRingerMode(int)
530 * @see #getRingerMode()
532 public static final int RINGER_MODE_SILENT = 0;
535 * Ringer mode that will be silent and will vibrate. (This will cause the
536 * phone ringer to always vibrate, but the notification vibrate to only
539 * @see #setRingerMode(int)
540 * @see #getRingerMode()
542 public static final int RINGER_MODE_VIBRATE = 1;
545 * Ringer mode that may be audible and may vibrate. It will be audible if
546 * the volume before changing out of this mode was audible. It will vibrate
547 * if the vibrate setting is on.
549 * @see #setRingerMode(int)
550 * @see #getRingerMode()
552 public static final int RINGER_MODE_NORMAL = 2;
555 * Maximum valid ringer mode value. Values must start from 0 and be contiguous.
558 public static final int RINGER_MODE_MAX = RINGER_MODE_NORMAL;
561 * Vibrate type that corresponds to the ringer.
563 * @see #setVibrateSetting(int, int)
564 * @see #getVibrateSetting(int)
565 * @see #shouldVibrate(int)
566 * @deprecated Applications should maintain their own vibrate policy based on
567 * current ringer mode that can be queried via {@link #getRingerMode()}.
569 public static final int VIBRATE_TYPE_RINGER = 0;
572 * Vibrate type that corresponds to notifications.
574 * @see #setVibrateSetting(int, int)
575 * @see #getVibrateSetting(int)
576 * @see #shouldVibrate(int)
577 * @deprecated Applications should maintain their own vibrate policy based on
578 * current ringer mode that can be queried via {@link #getRingerMode()}.
580 public static final int VIBRATE_TYPE_NOTIFICATION = 1;
583 * Vibrate setting that suggests to never vibrate.
585 * @see #setVibrateSetting(int, int)
586 * @see #getVibrateSetting(int)
587 * @deprecated Applications should maintain their own vibrate policy based on
588 * current ringer mode that can be queried via {@link #getRingerMode()}.
590 public static final int VIBRATE_SETTING_OFF = 0;
593 * Vibrate setting that suggests to vibrate when possible.
595 * @see #setVibrateSetting(int, int)
596 * @see #getVibrateSetting(int)
597 * @deprecated Applications should maintain their own vibrate policy based on
598 * current ringer mode that can be queried via {@link #getRingerMode()}.
600 public static final int VIBRATE_SETTING_ON = 1;
603 * Vibrate setting that suggests to only vibrate when in the vibrate ringer
606 * @see #setVibrateSetting(int, int)
607 * @see #getVibrateSetting(int)
608 * @deprecated Applications should maintain their own vibrate policy based on
609 * current ringer mode that can be queried via {@link #getRingerMode()}.
611 public static final int VIBRATE_SETTING_ONLY_SILENT = 2;
614 * Suggests using the default stream type. This may not be used in all
615 * places a stream type is needed.
617 public static final int USE_DEFAULT_STREAM_TYPE = Integer.MIN_VALUE;
619 private static IAudioService sService;
624 public AudioManager(Context context) {
626 mUseVolumeKeySounds = getContext().getResources().getBoolean(
627 com.android.internal.R.bool.config_useVolumeKeySounds);
628 mUseFixedVolume = getContext().getResources().getBoolean(
629 com.android.internal.R.bool.config_useFixedVolume);
630 sAudioPortEventHandler.init();
633 private Context getContext() {
634 if (mApplicationContext == null) {
635 setContext(mOriginalContext);
637 if (mApplicationContext != null) {
638 return mApplicationContext;
640 return mOriginalContext;
643 private void setContext(Context context) {
644 mApplicationContext = context.getApplicationContext();
645 if (mApplicationContext != null) {
646 mOriginalContext = null;
648 mOriginalContext = context;
652 private static IAudioService getService()
654 if (sService != null) {
657 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
658 sService = IAudioService.Stub.asInterface(b);
663 * Sends a simulated key event for a media button.
664 * To simulate a key press, you must first send a KeyEvent built with a
665 * {@link KeyEvent#ACTION_DOWN} action, then another event with the {@link KeyEvent#ACTION_UP}
667 * <p>The key event will be sent to the current media key event consumer which registered with
668 * {@link AudioManager#registerMediaButtonEventReceiver(PendingIntent)}.
669 * @param keyEvent a {@link KeyEvent} instance whose key code is one of
670 * {@link KeyEvent#KEYCODE_MUTE},
671 * {@link KeyEvent#KEYCODE_HEADSETHOOK},
672 * {@link KeyEvent#KEYCODE_MEDIA_PLAY},
673 * {@link KeyEvent#KEYCODE_MEDIA_PAUSE},
674 * {@link KeyEvent#KEYCODE_MEDIA_PLAY_PAUSE},
675 * {@link KeyEvent#KEYCODE_MEDIA_STOP},
676 * {@link KeyEvent#KEYCODE_MEDIA_NEXT},
677 * {@link KeyEvent#KEYCODE_MEDIA_PREVIOUS},
678 * {@link KeyEvent#KEYCODE_MEDIA_REWIND},
679 * {@link KeyEvent#KEYCODE_MEDIA_RECORD},
680 * {@link KeyEvent#KEYCODE_MEDIA_FAST_FORWARD},
681 * {@link KeyEvent#KEYCODE_MEDIA_CLOSE},
682 * {@link KeyEvent#KEYCODE_MEDIA_EJECT},
683 * or {@link KeyEvent#KEYCODE_MEDIA_AUDIO_TRACK}.
685 public void dispatchMediaKeyEvent(KeyEvent keyEvent) {
686 MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
687 helper.sendMediaButtonEvent(keyEvent, false);
693 public void preDispatchKeyEvent(KeyEvent event, int stream) {
695 * If the user hits another key within the play sound delay, then
698 int keyCode = event.getKeyCode();
699 if (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_UP
700 && keyCode != KeyEvent.KEYCODE_VOLUME_MUTE
701 && mVolumeKeyUpTime + AudioSystem.PLAY_SOUND_DELAY > SystemClock.uptimeMillis()) {
703 * The user has hit another key during the delay (e.g., 300ms)
704 * since the last volume key up, so cancel any sounds.
706 adjustSuggestedStreamVolume(ADJUST_SAME,
707 stream, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
714 public void handleKeyDown(KeyEvent event, int stream) {
715 int keyCode = event.getKeyCode();
717 case KeyEvent.KEYCODE_VOLUME_UP:
718 case KeyEvent.KEYCODE_VOLUME_DOWN:
720 * Adjust the volume in on key down since it is more
721 * responsive to the user.
723 adjustSuggestedStreamVolume(
724 keyCode == KeyEvent.KEYCODE_VOLUME_UP
728 FLAG_SHOW_UI | FLAG_VIBRATE);
730 case KeyEvent.KEYCODE_VOLUME_MUTE:
731 if (event.getRepeatCount() == 0) {
732 MediaSessionLegacyHelper.getHelper(getContext())
733 .sendVolumeKeyEvent(event, false);
742 public void handleKeyUp(KeyEvent event, int stream) {
743 int keyCode = event.getKeyCode();
745 case KeyEvent.KEYCODE_VOLUME_UP:
746 case KeyEvent.KEYCODE_VOLUME_DOWN:
748 * Play a sound. This is done on key up since we don't want the
749 * sound to play when a user holds down volume down to mute.
751 if (mUseVolumeKeySounds) {
752 adjustSuggestedStreamVolume(
757 mVolumeKeyUpTime = SystemClock.uptimeMillis();
759 case KeyEvent.KEYCODE_VOLUME_MUTE:
760 MediaSessionLegacyHelper.getHelper(getContext())
761 .sendVolumeKeyEvent(event, false);
767 * Indicates if the device implements a fixed volume policy.
768 * <p>Some devices may not have volume control and may operate at a fixed volume,
769 * and may not enable muting or changing the volume of audio streams.
770 * This method will return true on such devices.
771 * <p>The following APIs have no effect when volume is fixed:
773 * <li> {@link #adjustVolume(int, int)}
774 * <li> {@link #adjustSuggestedStreamVolume(int, int, int)}
775 * <li> {@link #adjustStreamVolume(int, int, int)}
776 * <li> {@link #setStreamVolume(int, int, int)}
777 * <li> {@link #setRingerMode(int)}
778 * <li> {@link #setStreamSolo(int, boolean)}
779 * <li> {@link #setStreamMute(int, boolean)}
782 public boolean isVolumeFixed() {
783 return mUseFixedVolume;
787 * Adjusts the volume of a particular stream by one step in a direction.
789 * This method should only be used by applications that replace the platform-wide
790 * management of audio settings or the main telephony application.
792 * @param streamType The stream type to adjust. One of {@link #STREAM_VOICE_CALL},
793 * {@link #STREAM_SYSTEM}, {@link #STREAM_RING}, {@link #STREAM_MUSIC} or
794 * {@link #STREAM_ALARM}
795 * @param direction The direction to adjust the volume. One of
796 * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE}, or
797 * {@link #ADJUST_SAME}.
798 * @param flags One or more flags.
799 * @see #adjustVolume(int, int)
800 * @see #setStreamVolume(int, int, int)
802 public void adjustStreamVolume(int streamType, int direction, int flags) {
803 IAudioService service = getService();
805 service.adjustStreamVolume(streamType, direction, flags,
806 getContext().getOpPackageName());
807 } catch (RemoteException e) {
808 Log.e(TAG, "Dead object in adjustStreamVolume", e);
813 * Adjusts the volume of the most relevant stream. For example, if a call is
814 * active, it will have the highest priority regardless of if the in-call
815 * screen is showing. Another example, if music is playing in the background
816 * and a call is not active, the music stream will be adjusted.
818 * This method should only be used by applications that replace the
819 * platform-wide management of audio settings or the main telephony
822 * This method has no effect if the device implements a fixed volume policy
823 * as indicated by {@link #isVolumeFixed()}.
825 * @param direction The direction to adjust the volume. One of
826 * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE},
827 * {@link #ADJUST_SAME}, {@link #ADJUST_MUTE},
828 * {@link #ADJUST_UNMUTE}, or {@link #ADJUST_TOGGLE_MUTE}.
829 * @param flags One or more flags.
830 * @see #adjustSuggestedStreamVolume(int, int, int)
831 * @see #adjustStreamVolume(int, int, int)
832 * @see #setStreamVolume(int, int, int)
833 * @see #isVolumeFixed()
835 public void adjustVolume(int direction, int flags) {
836 MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
837 helper.sendAdjustVolumeBy(USE_DEFAULT_STREAM_TYPE, direction, flags);
841 * Adjusts the volume of the most relevant stream, or the given fallback
844 * This method should only be used by applications that replace the
845 * platform-wide management of audio settings or the main telephony
848 * This method has no effect if the device implements a fixed volume policy
849 * as indicated by {@link #isVolumeFixed()}.
851 * @param direction The direction to adjust the volume. One of
852 * {@link #ADJUST_LOWER}, {@link #ADJUST_RAISE},
853 * {@link #ADJUST_SAME}, {@link #ADJUST_MUTE},
854 * {@link #ADJUST_UNMUTE}, or {@link #ADJUST_TOGGLE_MUTE}.
855 * @param suggestedStreamType The stream type that will be used if there
856 * isn't a relevant stream. {@link #USE_DEFAULT_STREAM_TYPE} is
858 * @param flags One or more flags.
859 * @see #adjustVolume(int, int)
860 * @see #adjustStreamVolume(int, int, int)
861 * @see #setStreamVolume(int, int, int)
862 * @see #isVolumeFixed()
864 public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
865 MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
866 helper.sendAdjustVolumeBy(suggestedStreamType, direction, flags);
870 public void setMasterMute(boolean mute, int flags) {
871 IAudioService service = getService();
873 service.setMasterMute(mute, flags, getContext().getOpPackageName());
874 } catch (RemoteException e) {
875 Log.e(TAG, "Dead object in setMasterMute", e);
880 * Returns the current ringtone mode.
882 * @return The current ringtone mode, one of {@link #RINGER_MODE_NORMAL},
883 * {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
884 * @see #setRingerMode(int)
886 public int getRingerMode() {
887 IAudioService service = getService();
889 return service.getRingerModeExternal();
890 } catch (RemoteException e) {
891 Log.e(TAG, "Dead object in getRingerMode", e);
892 return RINGER_MODE_NORMAL;
897 * Checks valid ringer mode values.
899 * @return true if the ringer mode indicated is valid, false otherwise.
901 * @see #setRingerMode(int)
904 public static boolean isValidRingerMode(int ringerMode) {
905 if (ringerMode < 0 || ringerMode > RINGER_MODE_MAX) {
908 IAudioService service = getService();
910 return service.isValidRingerMode(ringerMode);
911 } catch (RemoteException e) {
912 Log.e(TAG, "Dead object in isValidRingerMode", e);
918 * Returns the maximum volume index for a particular stream.
920 * @param streamType The stream type whose maximum volume index is returned.
921 * @return The maximum valid volume index for the stream.
922 * @see #getStreamVolume(int)
924 public int getStreamMaxVolume(int streamType) {
925 IAudioService service = getService();
927 return service.getStreamMaxVolume(streamType);
928 } catch (RemoteException e) {
929 Log.e(TAG, "Dead object in getStreamMaxVolume", e);
935 * Returns the minimum volume index for a particular stream.
937 * @param streamType The stream type whose minimum volume index is returned.
938 * @return The minimum valid volume index for the stream.
939 * @see #getStreamVolume(int)
942 public int getStreamMinVolume(int streamType) {
943 IAudioService service = getService();
945 return service.getStreamMinVolume(streamType);
946 } catch (RemoteException e) {
947 Log.e(TAG, "Dead object in getStreamMinVolume", e);
953 * Returns the current volume index for a particular stream.
955 * @param streamType The stream type whose volume index is returned.
956 * @return The current volume index for the stream.
957 * @see #getStreamMaxVolume(int)
958 * @see #setStreamVolume(int, int, int)
960 public int getStreamVolume(int streamType) {
961 IAudioService service = getService();
963 return service.getStreamVolume(streamType);
964 } catch (RemoteException e) {
965 Log.e(TAG, "Dead object in getStreamVolume", e);
971 * Get last audible volume before stream was muted.
975 public int getLastAudibleStreamVolume(int streamType) {
976 IAudioService service = getService();
978 return service.getLastAudibleStreamVolume(streamType);
979 } catch (RemoteException e) {
980 Log.e(TAG, "Dead object in getLastAudibleStreamVolume", e);
986 * Get the stream type whose volume is driving the UI sounds volume.
987 * UI sounds are screen lock/unlock, camera shutter, key clicks...
988 * It is assumed that this stream type is also tied to ringer mode changes.
991 public int getUiSoundsStreamType() {
992 IAudioService service = getService();
994 return service.getUiSoundsStreamType();
995 } catch (RemoteException e) {
996 Log.e(TAG, "Dead object in getUiSoundsStreamType", e);
1002 * Sets the ringer mode.
1004 * Silent mode will mute the volume and will not vibrate. Vibrate mode will
1005 * mute the volume and vibrate. Normal mode will be audible and may vibrate
1006 * according to user settings.
1007 * <p>This method has no effect if the device implements a fixed volume policy
1008 * as indicated by {@link #isVolumeFixed()}.
1009 * @param ringerMode The ringer mode, one of {@link #RINGER_MODE_NORMAL},
1010 * {@link #RINGER_MODE_SILENT}, or {@link #RINGER_MODE_VIBRATE}.
1011 * @see #getRingerMode()
1012 * @see #isVolumeFixed()
1014 public void setRingerMode(int ringerMode) {
1015 if (!isValidRingerMode(ringerMode)) {
1018 IAudioService service = getService();
1020 service.setRingerModeExternal(ringerMode, getContext().getOpPackageName());
1021 } catch (RemoteException e) {
1022 Log.e(TAG, "Dead object in setRingerMode", e);
1027 * Sets the volume index for a particular stream.
1028 * <p>This method has no effect if the device implements a fixed volume policy
1029 * as indicated by {@link #isVolumeFixed()}.
1030 * @param streamType The stream whose volume index should be set.
1031 * @param index The volume index to set. See
1032 * {@link #getStreamMaxVolume(int)} for the largest valid value.
1033 * @param flags One or more flags.
1034 * @see #getStreamMaxVolume(int)
1035 * @see #getStreamVolume(int)
1036 * @see #isVolumeFixed()
1038 public void setStreamVolume(int streamType, int index, int flags) {
1039 IAudioService service = getService();
1041 service.setStreamVolume(streamType, index, flags, getContext().getOpPackageName());
1042 } catch (RemoteException e) {
1043 Log.e(TAG, "Dead object in setStreamVolume", e);
1048 * Solo or unsolo a particular stream.
1050 * Do not use. This method has been deprecated and is now a no-op.
1051 * {@link #requestAudioFocus} should be used for exclusive audio playback.
1053 * @param streamType The stream to be soloed/unsoloed.
1054 * @param state The required solo state: true for solo ON, false for solo
1056 * @see #isVolumeFixed()
1057 * @deprecated Do not use. If you need exclusive audio playback use
1058 * {@link #requestAudioFocus}.
1061 public void setStreamSolo(int streamType, boolean state) {
1062 Log.w(TAG, "setStreamSolo has been deprecated. Do not use.");
1066 * Mute or unmute an audio stream.
1068 * This method should only be used by applications that replace the
1069 * platform-wide management of audio settings or the main telephony
1072 * This method has no effect if the device implements a fixed volume policy
1073 * as indicated by {@link #isVolumeFixed()}.
1075 * This method was deprecated in API level 22. Prior to API level 22 this
1076 * method had significantly different behavior and should be used carefully.
1077 * The following applies only to pre-22 platforms:
1079 * <li>The mute command is protected against client process death: if a
1080 * process with an active mute request on a stream dies, this stream will be
1081 * unmuted automatically.</li>
1082 * <li>The mute requests for a given stream are cumulative: the AudioManager
1083 * can receive several mute requests from one or more clients and the stream
1084 * will be unmuted only when the same number of unmute requests are
1086 * <li>For a better user experience, applications MUST unmute a muted stream
1087 * in onPause() and mute is again in onResume() if appropriate.</li>
1090 * @param streamType The stream to be muted/unmuted.
1091 * @param state The required mute state: true for mute ON, false for mute
1093 * @see #isVolumeFixed()
1094 * @deprecated Use {@link #adjustStreamVolume(int, int, int)} with
1095 * {@link #ADJUST_MUTE} or {@link #ADJUST_UNMUTE} instead.
1098 public void setStreamMute(int streamType, boolean state) {
1099 Log.w(TAG, "setStreamMute is deprecated. adjustStreamVolume should be used instead.");
1100 int direction = state ? ADJUST_MUTE : ADJUST_UNMUTE;
1101 if (streamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1102 adjustSuggestedStreamVolume(direction, streamType, 0);
1104 adjustStreamVolume(streamType, direction, 0);
1109 * Returns the current mute state for a particular stream.
1111 * @param streamType The stream to get mute state for.
1112 * @return The mute state for the given stream.
1113 * @see #adjustStreamVolume(int, int, int)
1115 public boolean isStreamMute(int streamType) {
1116 IAudioService service = getService();
1118 return service.isStreamMute(streamType);
1119 } catch (RemoteException e) {
1120 Log.e(TAG, "Dead object in isStreamMute", e);
1126 * get master mute state.
1130 public boolean isMasterMute() {
1131 IAudioService service = getService();
1133 return service.isMasterMute();
1134 } catch (RemoteException e) {
1135 Log.e(TAG, "Dead object in isMasterMute", e);
1141 * forces the stream controlled by hard volume keys
1142 * specifying streamType == -1 releases control to the
1147 public void forceVolumeControlStream(int streamType) {
1148 IAudioService service = getService();
1150 service.forceVolumeControlStream(streamType, mICallBack);
1151 } catch (RemoteException e) {
1152 Log.e(TAG, "Dead object in forceVolumeControlStream", e);
1157 * Returns whether a particular type should vibrate according to user
1158 * settings and the current ringer mode.
1160 * This shouldn't be needed by most clients that use notifications to
1161 * vibrate. The notification manager will not vibrate if the policy doesn't
1162 * allow it, so the client should always set a vibrate pattern and let the
1163 * notification manager control whether or not to actually vibrate.
1165 * @param vibrateType The type of vibrate. One of
1166 * {@link #VIBRATE_TYPE_NOTIFICATION} or
1167 * {@link #VIBRATE_TYPE_RINGER}.
1168 * @return Whether the type should vibrate at the instant this method is
1170 * @see #setVibrateSetting(int, int)
1171 * @see #getVibrateSetting(int)
1172 * @deprecated Applications should maintain their own vibrate policy based on
1173 * current ringer mode that can be queried via {@link #getRingerMode()}.
1175 public boolean shouldVibrate(int vibrateType) {
1176 IAudioService service = getService();
1178 return service.shouldVibrate(vibrateType);
1179 } catch (RemoteException e) {
1180 Log.e(TAG, "Dead object in shouldVibrate", e);
1186 * Returns whether the user's vibrate setting for a vibrate type.
1188 * This shouldn't be needed by most clients that want to vibrate, instead
1189 * see {@link #shouldVibrate(int)}.
1191 * @param vibrateType The type of vibrate. One of
1192 * {@link #VIBRATE_TYPE_NOTIFICATION} or
1193 * {@link #VIBRATE_TYPE_RINGER}.
1194 * @return The vibrate setting, one of {@link #VIBRATE_SETTING_ON},
1195 * {@link #VIBRATE_SETTING_OFF}, or
1196 * {@link #VIBRATE_SETTING_ONLY_SILENT}.
1197 * @see #setVibrateSetting(int, int)
1198 * @see #shouldVibrate(int)
1199 * @deprecated Applications should maintain their own vibrate policy based on
1200 * current ringer mode that can be queried via {@link #getRingerMode()}.
1202 public int getVibrateSetting(int vibrateType) {
1203 IAudioService service = getService();
1205 return service.getVibrateSetting(vibrateType);
1206 } catch (RemoteException e) {
1207 Log.e(TAG, "Dead object in getVibrateSetting", e);
1208 return VIBRATE_SETTING_OFF;
1213 * Sets the setting for when the vibrate type should vibrate.
1215 * This method should only be used by applications that replace the platform-wide
1216 * management of audio settings or the main telephony application.
1218 * @param vibrateType The type of vibrate. One of
1219 * {@link #VIBRATE_TYPE_NOTIFICATION} or
1220 * {@link #VIBRATE_TYPE_RINGER}.
1221 * @param vibrateSetting The vibrate setting, one of
1222 * {@link #VIBRATE_SETTING_ON},
1223 * {@link #VIBRATE_SETTING_OFF}, or
1224 * {@link #VIBRATE_SETTING_ONLY_SILENT}.
1225 * @see #getVibrateSetting(int)
1226 * @see #shouldVibrate(int)
1227 * @deprecated Applications should maintain their own vibrate policy based on
1228 * current ringer mode that can be queried via {@link #getRingerMode()}.
1230 public void setVibrateSetting(int vibrateType, int vibrateSetting) {
1231 IAudioService service = getService();
1233 service.setVibrateSetting(vibrateType, vibrateSetting);
1234 } catch (RemoteException e) {
1235 Log.e(TAG, "Dead object in setVibrateSetting", e);
1240 * Sets the speakerphone on or off.
1242 * This method should only be used by applications that replace the platform-wide
1243 * management of audio settings or the main telephony application.
1245 * @param on set <var>true</var> to turn on speakerphone;
1246 * <var>false</var> to turn it off
1248 public void setSpeakerphoneOn(boolean on){
1249 IAudioService service = getService();
1251 service.setSpeakerphoneOn(on);
1252 } catch (RemoteException e) {
1253 Log.e(TAG, "Dead object in setSpeakerphoneOn", e);
1258 * Checks whether the speakerphone is on or off.
1260 * @return true if speakerphone is on, false if it's off
1262 public boolean isSpeakerphoneOn() {
1263 IAudioService service = getService();
1265 return service.isSpeakerphoneOn();
1266 } catch (RemoteException e) {
1267 Log.e(TAG, "Dead object in isSpeakerphoneOn", e);
1272 //====================================================================
1273 // Bluetooth SCO control
1275 * Sticky broadcast intent action indicating that the bluetoooth SCO audio
1276 * connection state has changed. The intent contains on extra {@link #EXTRA_SCO_AUDIO_STATE}
1277 * indicating the new state which is either {@link #SCO_AUDIO_STATE_DISCONNECTED}
1278 * or {@link #SCO_AUDIO_STATE_CONNECTED}
1280 * @see #startBluetoothSco()
1281 * @deprecated Use {@link #ACTION_SCO_AUDIO_STATE_UPDATED} instead
1284 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1285 public static final String ACTION_SCO_AUDIO_STATE_CHANGED =
1286 "android.media.SCO_AUDIO_STATE_CHANGED";
1289 * Sticky broadcast intent action indicating that the bluetoooth SCO audio
1290 * connection state has been updated.
1291 * <p>This intent has two extras:
1293 * <li> {@link #EXTRA_SCO_AUDIO_STATE} - The new SCO audio state. </li>
1294 * <li> {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}- The previous SCO audio state. </li>
1296 * <p> EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE can be any of:
1298 * <li> {@link #SCO_AUDIO_STATE_DISCONNECTED}, </li>
1299 * <li> {@link #SCO_AUDIO_STATE_CONNECTING} or </li>
1300 * <li> {@link #SCO_AUDIO_STATE_CONNECTED}, </li>
1302 * @see #startBluetoothSco()
1304 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
1305 public static final String ACTION_SCO_AUDIO_STATE_UPDATED =
1306 "android.media.ACTION_SCO_AUDIO_STATE_UPDATED";
1309 * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_CHANGED} or
1310 * {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the new bluetooth SCO connection state.
1312 public static final String EXTRA_SCO_AUDIO_STATE =
1313 "android.media.extra.SCO_AUDIO_STATE";
1316 * Extra for intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED} containing the previous
1317 * bluetooth SCO connection state.
1319 public static final String EXTRA_SCO_AUDIO_PREVIOUS_STATE =
1320 "android.media.extra.SCO_AUDIO_PREVIOUS_STATE";
1323 * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
1324 * indicating that the SCO audio channel is not established
1326 public static final int SCO_AUDIO_STATE_DISCONNECTED = 0;
1328 * Value for extra {@link #EXTRA_SCO_AUDIO_STATE} or {@link #EXTRA_SCO_AUDIO_PREVIOUS_STATE}
1329 * indicating that the SCO audio channel is established
1331 public static final int SCO_AUDIO_STATE_CONNECTED = 1;
1333 * Value for extra EXTRA_SCO_AUDIO_STATE or EXTRA_SCO_AUDIO_PREVIOUS_STATE
1334 * indicating that the SCO audio channel is being established
1336 public static final int SCO_AUDIO_STATE_CONNECTING = 2;
1338 * Value for extra EXTRA_SCO_AUDIO_STATE indicating that
1339 * there was an error trying to obtain the state
1341 public static final int SCO_AUDIO_STATE_ERROR = -1;
1345 * Indicates if current platform supports use of SCO for off call use cases.
1346 * Application wanted to use bluetooth SCO audio when the phone is not in call
1347 * must first call this method to make sure that the platform supports this
1349 * @return true if bluetooth SCO can be used for audio when not in call
1351 * @see #startBluetoothSco()
1353 public boolean isBluetoothScoAvailableOffCall() {
1354 return getContext().getResources().getBoolean(
1355 com.android.internal.R.bool.config_bluetooth_sco_off_call);
1359 * Start bluetooth SCO audio connection.
1360 * <p>Requires Permission:
1361 * {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1362 * <p>This method can be used by applications wanting to send and received audio
1363 * to/from a bluetooth SCO headset while the phone is not in call.
1364 * <p>As the SCO connection establishment can take several seconds,
1365 * applications should not rely on the connection to be available when the method
1366 * returns but instead register to receive the intent {@link #ACTION_SCO_AUDIO_STATE_UPDATED}
1367 * and wait for the state to be {@link #SCO_AUDIO_STATE_CONNECTED}.
1368 * <p>As the ACTION_SCO_AUDIO_STATE_UPDATED intent is sticky, the application can check the SCO
1369 * audio state before calling startBluetoothSco() by reading the intent returned by the receiver
1370 * registration. If the state is already CONNECTED, no state change will be received via the
1371 * intent after calling startBluetoothSco(). It is however useful to call startBluetoothSco()
1372 * so that the connection stays active in case the current initiator stops the connection.
1373 * <p>Unless the connection is already active as described above, the state will always
1374 * transition from DISCONNECTED to CONNECTING and then either to CONNECTED if the connection
1375 * succeeds or back to DISCONNECTED if the connection fails (e.g no headset is connected).
1376 * <p>When finished with the SCO connection or if the establishment fails, the application must
1377 * call {@link #stopBluetoothSco()} to clear the request and turn down the bluetooth connection.
1378 * <p>Even if a SCO connection is established, the following restrictions apply on audio
1379 * output streams so that they can be routed to SCO headset:
1381 * <li> the stream type must be {@link #STREAM_VOICE_CALL} </li>
1382 * <li> the format must be mono </li>
1383 * <li> the sampling must be 16kHz or 8kHz </li>
1385 * <p>The following restrictions apply on input streams:
1387 * <li> the format must be mono </li>
1388 * <li> the sampling must be 8kHz </li>
1390 * <p>Note that the phone application always has the priority on the usage of the SCO
1391 * connection for telephony. If this method is called while the phone is in call
1392 * it will be ignored. Similarly, if a call is received or sent while an application
1393 * is using the SCO connection, the connection will be lost for the application and NOT
1394 * returned automatically when the call ends.
1395 * <p>NOTE: up to and including API version
1396 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}, this method initiates a virtual
1397 * voice call to the bluetooth headset.
1398 * After API version {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} only a raw SCO audio
1399 * connection is established.
1400 * @see #stopBluetoothSco()
1401 * @see #ACTION_SCO_AUDIO_STATE_UPDATED
1403 public void startBluetoothSco(){
1404 IAudioService service = getService();
1406 service.startBluetoothSco(mICallBack,
1407 getContext().getApplicationInfo().targetSdkVersion);
1408 } catch (RemoteException e) {
1409 Log.e(TAG, "Dead object in startBluetoothSco", e);
1415 * Start bluetooth SCO audio connection in virtual call mode.
1416 * <p>Requires Permission:
1417 * {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1418 * <p>Similar to {@link #startBluetoothSco()} with explicit selection of virtual call mode.
1419 * Telephony and communication applications (VoIP, Video Chat) should preferably select
1420 * virtual call mode.
1421 * Applications using voice input for search or commands should first try raw audio connection
1422 * with {@link #startBluetoothSco()} and fall back to startBluetoothScoVirtualCall() in case of
1424 * @see #startBluetoothSco()
1425 * @see #stopBluetoothSco()
1426 * @see #ACTION_SCO_AUDIO_STATE_UPDATED
1428 public void startBluetoothScoVirtualCall() {
1429 IAudioService service = getService();
1431 service.startBluetoothScoVirtualCall(mICallBack);
1432 } catch (RemoteException e) {
1433 Log.e(TAG, "Dead object in startBluetoothScoVirtualCall", e);
1438 * Stop bluetooth SCO audio connection.
1439 * <p>Requires Permission:
1440 * {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}.
1441 * <p>This method must be called by applications having requested the use of
1442 * bluetooth SCO audio with {@link #startBluetoothSco()} when finished with the SCO
1443 * connection or if connection fails.
1444 * @see #startBluetoothSco()
1446 // Also used for connections started with {@link #startBluetoothScoVirtualCall()}
1447 public void stopBluetoothSco(){
1448 IAudioService service = getService();
1450 service.stopBluetoothSco(mICallBack);
1451 } catch (RemoteException e) {
1452 Log.e(TAG, "Dead object in stopBluetoothSco", e);
1457 * Request use of Bluetooth SCO headset for communications.
1459 * This method should only be used by applications that replace the platform-wide
1460 * management of audio settings or the main telephony application.
1462 * @param on set <var>true</var> to use bluetooth SCO for communications;
1463 * <var>false</var> to not use bluetooth SCO for communications
1465 public void setBluetoothScoOn(boolean on){
1466 IAudioService service = getService();
1468 service.setBluetoothScoOn(on);
1469 } catch (RemoteException e) {
1470 Log.e(TAG, "Dead object in setBluetoothScoOn", e);
1475 * Checks whether communications use Bluetooth SCO.
1477 * @return true if SCO is used for communications;
1478 * false if otherwise
1480 public boolean isBluetoothScoOn() {
1481 IAudioService service = getService();
1483 return service.isBluetoothScoOn();
1484 } catch (RemoteException e) {
1485 Log.e(TAG, "Dead object in isBluetoothScoOn", e);
1491 * @param on set <var>true</var> to route A2DP audio to/from Bluetooth
1492 * headset; <var>false</var> disable A2DP audio
1493 * @deprecated Do not use.
1495 @Deprecated public void setBluetoothA2dpOn(boolean on){
1499 * Checks whether A2DP audio routing to the Bluetooth headset is on or off.
1501 * @return true if A2DP audio is being routed to/from Bluetooth headset;
1502 * false if otherwise
1504 public boolean isBluetoothA2dpOn() {
1505 if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_BLUETOOTH_A2DP,"")
1506 == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
1514 * Sets audio routing to the wired headset on or off.
1516 * @param on set <var>true</var> to route audio to/from wired
1517 * headset; <var>false</var> disable wired headset audio
1518 * @deprecated Do not use.
1520 @Deprecated public void setWiredHeadsetOn(boolean on){
1524 * Checks whether a wired headset is connected or not.
1525 * <p>This is not a valid indication that audio playback is
1526 * actually over the wired headset as audio routing depends on other conditions.
1528 * @return true if a wired headset is connected.
1529 * false if otherwise
1530 * @deprecated Use only to check is a headset is connected or not.
1532 public boolean isWiredHeadsetOn() {
1533 if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADSET,"")
1534 == AudioSystem.DEVICE_STATE_UNAVAILABLE &&
1535 AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE,"")
1536 == AudioSystem.DEVICE_STATE_UNAVAILABLE) {
1544 * Sets the microphone mute on or off.
1546 * This method should only be used by applications that replace the platform-wide
1547 * management of audio settings or the main telephony application.
1549 * @param on set <var>true</var> to mute the microphone;
1550 * <var>false</var> to turn mute off
1552 public void setMicrophoneMute(boolean on){
1553 IAudioService service = getService();
1555 service.setMicrophoneMute(on, getContext().getOpPackageName());
1556 } catch (RemoteException e) {
1557 Log.e(TAG, "Dead object in setMicrophoneMute", e);
1562 * Checks whether the microphone mute is on or off.
1564 * @return true if microphone is muted, false if it's not
1566 public boolean isMicrophoneMute() {
1567 return AudioSystem.isMicrophoneMuted();
1571 * Sets the audio mode.
1573 * The audio mode encompasses audio routing AND the behavior of
1574 * the telephony layer. Therefore this method should only be used by applications that
1575 * replace the platform-wide management of audio settings or the main telephony application.
1576 * In particular, the {@link #MODE_IN_CALL} mode should only be used by the telephony
1577 * application when it places a phone call, as it will cause signals from the radio layer
1578 * to feed the platform mixer.
1580 * @param mode the requested audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
1581 * {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
1582 * Informs the HAL about the current audio state so that
1583 * it can route the audio appropriately.
1585 public void setMode(int mode) {
1586 IAudioService service = getService();
1588 service.setMode(mode, mICallBack, mApplicationContext.getOpPackageName());
1589 } catch (RemoteException e) {
1590 Log.e(TAG, "Dead object in setMode", e);
1595 * Returns the current audio mode.
1597 * @return the current audio mode ({@link #MODE_NORMAL}, {@link #MODE_RINGTONE},
1598 * {@link #MODE_IN_CALL} or {@link #MODE_IN_COMMUNICATION}).
1599 * Returns the current current audio state from the HAL.
1601 public int getMode() {
1602 IAudioService service = getService();
1604 return service.getMode();
1605 } catch (RemoteException e) {
1606 Log.e(TAG, "Dead object in getMode", e);
1607 return MODE_INVALID;
1611 /* modes for setMode/getMode/setRoute/getRoute */
1613 * Audio harware modes.
1616 * Invalid audio mode.
1618 public static final int MODE_INVALID = AudioSystem.MODE_INVALID;
1620 * Current audio mode. Used to apply audio routing to current mode.
1622 public static final int MODE_CURRENT = AudioSystem.MODE_CURRENT;
1624 * Normal audio mode: not ringing and no call established.
1626 public static final int MODE_NORMAL = AudioSystem.MODE_NORMAL;
1628 * Ringing audio mode. An incoming is being signaled.
1630 public static final int MODE_RINGTONE = AudioSystem.MODE_RINGTONE;
1632 * In call audio mode. A telephony call is established.
1634 public static final int MODE_IN_CALL = AudioSystem.MODE_IN_CALL;
1636 * In communication audio mode. An audio/video chat or VoIP call is established.
1638 public static final int MODE_IN_COMMUNICATION = AudioSystem.MODE_IN_COMMUNICATION;
1640 /* Routing bits for setRouting/getRouting API */
1642 * Routing audio output to earpiece
1643 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1644 * setBluetoothScoOn() methods instead.
1646 @Deprecated public static final int ROUTE_EARPIECE = AudioSystem.ROUTE_EARPIECE;
1648 * Routing audio output to speaker
1649 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1650 * setBluetoothScoOn() methods instead.
1652 @Deprecated public static final int ROUTE_SPEAKER = AudioSystem.ROUTE_SPEAKER;
1654 * @deprecated use {@link #ROUTE_BLUETOOTH_SCO}
1655 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1656 * setBluetoothScoOn() methods instead.
1658 @Deprecated public static final int ROUTE_BLUETOOTH = AudioSystem.ROUTE_BLUETOOTH_SCO;
1660 * Routing audio output to bluetooth SCO
1661 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1662 * setBluetoothScoOn() methods instead.
1664 @Deprecated public static final int ROUTE_BLUETOOTH_SCO = AudioSystem.ROUTE_BLUETOOTH_SCO;
1666 * Routing audio output to headset
1667 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1668 * setBluetoothScoOn() methods instead.
1670 @Deprecated public static final int ROUTE_HEADSET = AudioSystem.ROUTE_HEADSET;
1672 * Routing audio output to bluetooth A2DP
1673 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1674 * setBluetoothScoOn() methods instead.
1676 @Deprecated public static final int ROUTE_BLUETOOTH_A2DP = AudioSystem.ROUTE_BLUETOOTH_A2DP;
1678 * Used for mask parameter of {@link #setRouting(int,int,int)}.
1679 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1680 * setBluetoothScoOn() methods instead.
1682 @Deprecated public static final int ROUTE_ALL = AudioSystem.ROUTE_ALL;
1685 * Sets the audio routing for a specified mode
1687 * @param mode audio mode to change route. E.g., MODE_RINGTONE.
1688 * @param routes bit vector of routes requested, created from one or
1689 * more of ROUTE_xxx types. Set bits indicate that route should be on
1690 * @param mask bit vector of routes to change, created from one or more of
1691 * ROUTE_xxx types. Unset bits indicate the route should be left unchanged
1693 * @deprecated Do not set audio routing directly, use setSpeakerphoneOn(),
1694 * setBluetoothScoOn() methods instead.
1697 public void setRouting(int mode, int routes, int mask) {
1701 * Returns the current audio routing bit vector for a specified mode.
1703 * @param mode audio mode to get route (e.g., MODE_RINGTONE)
1704 * @return an audio route bit vector that can be compared with ROUTE_xxx
1706 * @deprecated Do not query audio routing directly, use isSpeakerphoneOn(),
1707 * isBluetoothScoOn(), isBluetoothA2dpOn() and isWiredHeadsetOn() methods instead.
1710 public int getRouting(int mode) {
1715 * Checks whether any music is active.
1717 * @return true if any music tracks are active.
1719 public boolean isMusicActive() {
1720 return AudioSystem.isStreamActive(STREAM_MUSIC, 0);
1725 * Checks whether any music or media is actively playing on a remote device (e.g. wireless
1726 * display). Note that BT audio sinks are not considered remote devices.
1727 * @return true if {@link AudioManager#STREAM_MUSIC} is active on a remote device
1729 public boolean isMusicActiveRemotely() {
1730 return AudioSystem.isStreamActiveRemotely(STREAM_MUSIC, 0);
1735 * Checks whether the current audio focus is exclusive.
1736 * @return true if the top of the audio focus stack requested focus
1737 * with {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE}
1739 public boolean isAudioFocusExclusive() {
1740 IAudioService service = getService();
1742 return service.getCurrentAudioFocus() == AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE;
1743 } catch (RemoteException e) {
1744 Log.e(TAG, "Dead object in isAudioFocusExclusive()", e);
1750 * Return a new audio session identifier not associated with any player or effect.
1751 * An audio session identifier is a system wide unique identifier for a set of audio streams
1752 * (one or more mixed together).
1753 * <p>The primary use of the audio session ID is to associate audio effects to audio players,
1754 * such as {@link MediaPlayer} or {@link AudioTrack}: all audio effects sharing the same audio
1755 * session ID will be applied to the mixed audio content of the players that share the same
1757 * <p>This method can for instance be used when creating one of the
1758 * {@link android.media.audiofx.AudioEffect} objects to define the audio session of the effect,
1759 * or to specify a session for a speech synthesis utterance
1760 * in {@link android.speech.tts.TextToSpeech.Engine}.
1761 * @return a new unclaimed and unused audio session identifier, or {@link #ERROR} when the
1762 * system failed to generate a new session, a condition in which audio playback or recording
1763 * will subsequently fail as well.
1765 public int generateAudioSessionId() {
1766 int session = AudioSystem.newAudioSessionId();
1770 Log.e(TAG, "Failure to generate a new audio session ID");
1776 * A special audio session ID to indicate that the audio session ID isn't known and the
1777 * framework should generate a new value. This can be used when building a new
1778 * {@link AudioTrack} instance with
1779 * {@link AudioTrack#AudioTrack(AudioAttributes, AudioFormat, int, int, int)}.
1781 public static final int AUDIO_SESSION_ID_GENERATE = AudioSystem.AUDIO_SESSION_ALLOCATE;
1785 * Sets a generic audio configuration parameter. The use of these parameters
1786 * are platform dependant, see libaudio
1788 * ** Temporary interface - DO NOT USE
1790 * TODO: Replace with a more generic key:value get/set mechanism
1792 * param key name of parameter to set. Must not be null.
1793 * param value value of parameter. Must not be null.
1797 * @deprecated Use {@link #setParameters(String)} instead
1799 @Deprecated public void setParameter(String key, String value) {
1800 setParameters(key+"="+value);
1804 * Sets a variable number of parameter values to audio hardware.
1806 * @param keyValuePairs list of parameters key value pairs in the form:
1807 * key1=value1;key2=value2;...
1810 public void setParameters(String keyValuePairs) {
1811 AudioSystem.setParameters(keyValuePairs);
1815 * Gets a variable number of parameter values from audio hardware.
1817 * @param keys list of parameters
1818 * @return list of parameters key value pairs in the form:
1819 * key1=value1;key2=value2;...
1821 public String getParameters(String keys) {
1822 return AudioSystem.getParameters(keys);
1825 /* Sound effect identifiers */
1827 * Keyboard and direction pad click sound
1828 * @see #playSoundEffect(int)
1830 public static final int FX_KEY_CLICK = 0;
1832 * Focus has moved up
1833 * @see #playSoundEffect(int)
1835 public static final int FX_FOCUS_NAVIGATION_UP = 1;
1837 * Focus has moved down
1838 * @see #playSoundEffect(int)
1840 public static final int FX_FOCUS_NAVIGATION_DOWN = 2;
1842 * Focus has moved left
1843 * @see #playSoundEffect(int)
1845 public static final int FX_FOCUS_NAVIGATION_LEFT = 3;
1847 * Focus has moved right
1848 * @see #playSoundEffect(int)
1850 public static final int FX_FOCUS_NAVIGATION_RIGHT = 4;
1852 * IME standard keypress sound
1853 * @see #playSoundEffect(int)
1855 public static final int FX_KEYPRESS_STANDARD = 5;
1857 * IME spacebar keypress sound
1858 * @see #playSoundEffect(int)
1860 public static final int FX_KEYPRESS_SPACEBAR = 6;
1862 * IME delete keypress sound
1863 * @see #playSoundEffect(int)
1865 public static final int FX_KEYPRESS_DELETE = 7;
1867 * IME return_keypress sound
1868 * @see #playSoundEffect(int)
1870 public static final int FX_KEYPRESS_RETURN = 8;
1873 * Invalid keypress sound
1874 * @see #playSoundEffect(int)
1876 public static final int FX_KEYPRESS_INVALID = 9;
1878 * @hide Number of sound effects
1880 public static final int NUM_SOUND_EFFECTS = 10;
1883 * Plays a sound effect (Key clicks, lid open/close...)
1884 * @param effectType The type of sound effect. One of
1885 * {@link #FX_KEY_CLICK},
1886 * {@link #FX_FOCUS_NAVIGATION_UP},
1887 * {@link #FX_FOCUS_NAVIGATION_DOWN},
1888 * {@link #FX_FOCUS_NAVIGATION_LEFT},
1889 * {@link #FX_FOCUS_NAVIGATION_RIGHT},
1890 * {@link #FX_KEYPRESS_STANDARD},
1891 * {@link #FX_KEYPRESS_SPACEBAR},
1892 * {@link #FX_KEYPRESS_DELETE},
1893 * {@link #FX_KEYPRESS_RETURN},
1894 * {@link #FX_KEYPRESS_INVALID},
1895 * NOTE: This version uses the UI settings to determine
1896 * whether sounds are heard or not.
1898 public void playSoundEffect(int effectType) {
1899 if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
1903 if (!querySoundEffectsEnabled(Process.myUserHandle().getIdentifier())) {
1907 IAudioService service = getService();
1909 service.playSoundEffect(effectType);
1910 } catch (RemoteException e) {
1911 Log.e(TAG, "Dead object in playSoundEffect"+e);
1916 * Plays a sound effect (Key clicks, lid open/close...)
1917 * @param effectType The type of sound effect. One of
1918 * {@link #FX_KEY_CLICK},
1919 * {@link #FX_FOCUS_NAVIGATION_UP},
1920 * {@link #FX_FOCUS_NAVIGATION_DOWN},
1921 * {@link #FX_FOCUS_NAVIGATION_LEFT},
1922 * {@link #FX_FOCUS_NAVIGATION_RIGHT},
1923 * {@link #FX_KEYPRESS_STANDARD},
1924 * {@link #FX_KEYPRESS_SPACEBAR},
1925 * {@link #FX_KEYPRESS_DELETE},
1926 * {@link #FX_KEYPRESS_RETURN},
1927 * {@link #FX_KEYPRESS_INVALID},
1928 * @param userId The current user to pull sound settings from
1929 * NOTE: This version uses the UI settings to determine
1930 * whether sounds are heard or not.
1933 public void playSoundEffect(int effectType, int userId) {
1934 if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
1938 if (!querySoundEffectsEnabled(userId)) {
1942 IAudioService service = getService();
1944 service.playSoundEffect(effectType);
1945 } catch (RemoteException e) {
1946 Log.e(TAG, "Dead object in playSoundEffect"+e);
1951 * Plays a sound effect (Key clicks, lid open/close...)
1952 * @param effectType The type of sound effect. One of
1953 * {@link #FX_KEY_CLICK},
1954 * {@link #FX_FOCUS_NAVIGATION_UP},
1955 * {@link #FX_FOCUS_NAVIGATION_DOWN},
1956 * {@link #FX_FOCUS_NAVIGATION_LEFT},
1957 * {@link #FX_FOCUS_NAVIGATION_RIGHT},
1958 * {@link #FX_KEYPRESS_STANDARD},
1959 * {@link #FX_KEYPRESS_SPACEBAR},
1960 * {@link #FX_KEYPRESS_DELETE},
1961 * {@link #FX_KEYPRESS_RETURN},
1962 * {@link #FX_KEYPRESS_INVALID},
1963 * @param volume Sound effect volume.
1964 * The volume value is a raw scalar so UI controls should be scaled logarithmically.
1965 * If a volume of -1 is specified, the AudioManager.STREAM_MUSIC stream volume minus 3dB will be used.
1966 * NOTE: This version is for applications that have their own
1967 * settings panel for enabling and controlling volume.
1969 public void playSoundEffect(int effectType, float volume) {
1970 if (effectType < 0 || effectType >= NUM_SOUND_EFFECTS) {
1974 IAudioService service = getService();
1976 service.playSoundEffectVolume(effectType, volume);
1977 } catch (RemoteException e) {
1978 Log.e(TAG, "Dead object in playSoundEffect"+e);
1983 * Settings has an in memory cache, so this is fast.
1985 private boolean querySoundEffectsEnabled(int user) {
1986 return Settings.System.getIntForUser(getContext().getContentResolver(),
1987 Settings.System.SOUND_EFFECTS_ENABLED, 0, user) != 0;
1992 * Load Sound effects.
1993 * This method must be called when sound effects are enabled.
1995 public void loadSoundEffects() {
1996 IAudioService service = getService();
1998 service.loadSoundEffects();
1999 } catch (RemoteException e) {
2000 Log.e(TAG, "Dead object in loadSoundEffects"+e);
2005 * Unload Sound effects.
2006 * This method can be called to free some memory when
2007 * sound effects are disabled.
2009 public void unloadSoundEffects() {
2010 IAudioService service = getService();
2012 service.unloadSoundEffects();
2013 } catch (RemoteException e) {
2014 Log.e(TAG, "Dead object in unloadSoundEffects"+e);
2020 * Used to indicate no audio focus has been gained or lost.
2022 public static final int AUDIOFOCUS_NONE = 0;
2025 * Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
2026 * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2027 * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2029 public static final int AUDIOFOCUS_GAIN = 1;
2031 * Used to indicate a temporary gain or request of audio focus, anticipated to last a short
2032 * amount of time. Examples of temporary changes are the playback of driving directions, or an
2033 * event notification.
2034 * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2035 * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2037 public static final int AUDIOFOCUS_GAIN_TRANSIENT = 2;
2039 * Used to indicate a temporary request of audio focus, anticipated to last a short
2040 * amount of time, and where it is acceptable for other audio applications to keep playing
2041 * after having lowered their output level (also referred to as "ducking").
2042 * Examples of temporary changes are the playback of driving directions where playback of music
2043 * in the background is acceptable.
2044 * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2045 * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2047 public static final int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;
2049 * Used to indicate a temporary request of audio focus, anticipated to last a short
2050 * amount of time, during which no other applications, or system components, should play
2051 * anything. Examples of exclusive and transient audio focus requests are voice
2052 * memo recording and speech recognition, during which the system shouldn't play any
2053 * notifications, and media playback should have paused.
2054 * @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
2056 public static final int AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE = 4;
2058 * Used to indicate a loss of audio focus of unknown duration.
2059 * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2061 public static final int AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN;
2063 * Used to indicate a transient loss of audio focus.
2064 * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2066 public static final int AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT;
2068 * Used to indicate a transient loss of audio focus where the loser of the audio focus can
2069 * lower its output volume if it wants to continue playing (also referred to as "ducking"), as
2070 * the new focus owner doesn't require others to be silent.
2071 * @see OnAudioFocusChangeListener#onAudioFocusChange(int)
2073 public static final int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
2074 -1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
2077 * Interface definition for a callback to be invoked when the audio focus of the system is
2080 public interface OnAudioFocusChangeListener {
2082 * Called on the listener to notify it the audio focus for this listener has been changed.
2083 * The focusChange value indicates whether the focus was gained,
2084 * whether the focus was lost, and whether that loss is transient, or whether the new focus
2085 * holder will hold it for an unknown amount of time.
2086 * When losing focus, listeners can use the focus change information to decide what
2087 * behavior to adopt when losing focus. A music player could for instance elect to lower
2088 * the volume of its music stream (duck) for transient focus losses, and pause otherwise.
2089 * @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
2090 * {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
2091 * and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
2093 public void onAudioFocusChange(int focusChange);
2097 * Map to convert focus event listener IDs, as used in the AudioService audio focus stack,
2098 * to actual listener objects.
2100 private final HashMap<String, OnAudioFocusChangeListener> mAudioFocusIdListenerMap =
2101 new HashMap<String, OnAudioFocusChangeListener>();
2103 * Lock to prevent concurrent changes to the list of focus listeners for this AudioManager
2106 private final Object mFocusListenerLock = new Object();
2108 private OnAudioFocusChangeListener findFocusListener(String id) {
2109 return mAudioFocusIdListenerMap.get(id);
2113 * Handler for audio focus events coming from the audio service.
2115 private final FocusEventHandlerDelegate mAudioFocusEventHandlerDelegate =
2116 new FocusEventHandlerDelegate();
2119 * Helper class to handle the forwarding of audio focus events to the appropriate listener
2121 private class FocusEventHandlerDelegate {
2122 private final Handler mHandler;
2124 FocusEventHandlerDelegate() {
2126 if ((looper = Looper.myLooper()) == null) {
2127 looper = Looper.getMainLooper();
2130 if (looper != null) {
2131 // implement the event handler delegate to receive audio focus events
2132 mHandler = new Handler(looper) {
2134 public void handleMessage(Message msg) {
2135 OnAudioFocusChangeListener listener = null;
2136 synchronized(mFocusListenerLock) {
2137 listener = findFocusListener((String)msg.obj);
2139 if (listener != null) {
2140 Log.d(TAG, "AudioManager dispatching onAudioFocusChange("
2141 + msg.what + ") for " + msg.obj);
2142 listener.onAudioFocusChange(msg.what);
2151 Handler getHandler() {
2156 private final IAudioFocusDispatcher mAudioFocusDispatcher = new IAudioFocusDispatcher.Stub() {
2158 public void dispatchAudioFocusChange(int focusChange, String id) {
2159 Message m = mAudioFocusEventHandlerDelegate.getHandler().obtainMessage(focusChange, id);
2160 mAudioFocusEventHandlerDelegate.getHandler().sendMessage(m);
2165 private String getIdForAudioFocusListener(OnAudioFocusChangeListener l) {
2167 return new String(this.toString());
2169 return new String(this.toString() + l.toString());
2175 * Registers a listener to be called when audio focus changes. Calling this method is optional
2176 * before calling {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, as it
2177 * will register the listener as well if it wasn't registered already.
2178 * @param l the listener to be notified of audio focus changes.
2180 public void registerAudioFocusListener(OnAudioFocusChangeListener l) {
2181 synchronized(mFocusListenerLock) {
2182 if (mAudioFocusIdListenerMap.containsKey(getIdForAudioFocusListener(l))) {
2185 mAudioFocusIdListenerMap.put(getIdForAudioFocusListener(l), l);
2191 * Causes the specified listener to not be called anymore when focus is gained or lost.
2192 * @param l the listener to unregister.
2194 public void unregisterAudioFocusListener(OnAudioFocusChangeListener l) {
2197 synchronized(mFocusListenerLock) {
2198 mAudioFocusIdListenerMap.remove(getIdForAudioFocusListener(l));
2204 * A failed focus change request.
2206 public static final int AUDIOFOCUS_REQUEST_FAILED = 0;
2208 * A successful focus change request.
2210 public static final int AUDIOFOCUS_REQUEST_GRANTED = 1;
2213 * A focus change request whose granting is delayed: the request was successful, but the
2214 * requester will only be granted audio focus once the condition that prevented immediate
2215 * granting has ended.
2216 * See {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2218 public static final int AUDIOFOCUS_REQUEST_DELAYED = 2;
2222 * Request audio focus.
2223 * Send a request to obtain the audio focus
2224 * @param l the listener to be notified of audio focus changes
2225 * @param streamType the main audio stream type affected by the focus request
2226 * @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
2227 * is temporary, and focus will be abandonned shortly. Examples of transient requests are
2228 * for the playback of driving directions, or notifications sounds.
2229 * Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
2230 * the previous focus owner to keep playing if it ducks its audio output.
2231 * Alternatively use {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE} for a temporary request
2232 * that benefits from the system not playing disruptive sounds like notifications, for
2233 * usecases such as voice memo recording, or speech recognition.
2234 * Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
2235 * as the playback of a song or a video.
2236 * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
2238 public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) {
2239 int status = AUDIOFOCUS_REQUEST_FAILED;
2242 // status is guaranteed to be either AUDIOFOCUS_REQUEST_FAILED or
2243 // AUDIOFOCUS_REQUEST_GRANTED as focus is requested without the
2244 // AUDIOFOCUS_FLAG_DELAY_OK flag
2245 status = requestAudioFocus(l,
2246 new AudioAttributes.Builder()
2247 .setInternalLegacyStreamType(streamType).build(),
2249 0 /* flags, legacy behavior */);
2250 } catch (IllegalArgumentException e) {
2251 Log.e(TAG, "Audio focus request denied due to ", e);
2257 // when adding new flags, add them to the relevant AUDIOFOCUS_FLAGS_APPS or SYSTEM masks
2260 * Use this flag when requesting audio focus to indicate it is ok for the requester to not be
2261 * granted audio focus immediately (as indicated by {@link #AUDIOFOCUS_REQUEST_DELAYED}) when
2262 * the system is in a state where focus cannot change, but be granted focus later when
2263 * this condition ends.
2266 public static final int AUDIOFOCUS_FLAG_DELAY_OK = 0x1 << 0;
2269 * Use this flag when requesting audio focus to indicate that the requester
2270 * will pause its media playback (if applicable) when losing audio focus with
2271 * {@link #AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}, rather than ducking.
2272 * <br>On some platforms, the ducking may be handled without the application being aware of it
2273 * (i.e. it will not transiently lose focus). For applications that for instance play spoken
2274 * content, such as audio book or podcast players, ducking may never be acceptable, and will
2275 * thus always pause. This flag enables them to be declared as such whenever they request focus.
2278 public static final int AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS = 0x1 << 1;
2281 * Use this flag to lock audio focus so granting is temporarily disabled.
2282 * <br>This flag can only be used by owners of a registered
2283 * {@link android.media.audiopolicy.AudioPolicy} in
2284 * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int, AudioPolicy)}
2287 public static final int AUDIOFOCUS_FLAG_LOCK = 0x1 << 2;
2289 public static final int AUDIOFOCUS_FLAGS_APPS = AUDIOFOCUS_FLAG_DELAY_OK
2290 | AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS;
2292 public static final int AUDIOFOCUS_FLAGS_SYSTEM = AUDIOFOCUS_FLAG_DELAY_OK
2293 | AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS | AUDIOFOCUS_FLAG_LOCK;
2297 * Request audio focus.
2298 * Send a request to obtain the audio focus. This method differs from
2299 * {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)} in that it can express
2300 * that the requester accepts delayed grants of audio focus.
2301 * @param l the listener to be notified of audio focus changes. It is not allowed to be null
2302 * when the request is flagged with {@link #AUDIOFOCUS_FLAG_DELAY_OK}.
2303 * @param requestAttributes non null {@link AudioAttributes} describing the main reason for
2304 * requesting audio focus.
2305 * @param durationHint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} to indicate this focus request
2306 * is temporary, and focus will be abandonned shortly. Examples of transient requests are
2307 * for the playback of driving directions, or notifications sounds.
2308 * Use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK} to indicate also that it's ok for
2309 * the previous focus owner to keep playing if it ducks its audio output.
2310 * Alternatively use {@link #AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE} for a temporary request
2311 * that benefits from the system not playing disruptive sounds like notifications, for
2312 * usecases such as voice memo recording, or speech recognition.
2313 * Use {@link #AUDIOFOCUS_GAIN} for a focus request of unknown duration such
2314 * as the playback of a song or a video.
2315 * @param flags 0 or a combination of {link #AUDIOFOCUS_FLAG_DELAY_OK}
2316 * and {@link #AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS}.
2317 * <br>Use 0 when not using any flags for the request, which behaves like
2318 * {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, where either audio
2319 * focus is granted immediately, or the grant request fails because the system is in a
2320 * state where focus cannot change (e.g. a phone call).
2321 * @return {@link #AUDIOFOCUS_REQUEST_FAILED}, {@link #AUDIOFOCUS_REQUEST_GRANTED}
2322 * or {@link #AUDIOFOCUS_REQUEST_DELAYED}.
2323 * The return value is never {@link #AUDIOFOCUS_REQUEST_DELAYED} when focus is requested
2324 * without the {@link #AUDIOFOCUS_FLAG_DELAY_OK} flag.
2325 * @throws IllegalArgumentException
2328 public int requestAudioFocus(OnAudioFocusChangeListener l,
2329 @NonNull AudioAttributes requestAttributes,
2331 int flags) throws IllegalArgumentException {
2332 if (flags != (flags & AUDIOFOCUS_FLAGS_APPS)) {
2333 throw new IllegalArgumentException("Invalid flags 0x"
2334 + Integer.toHexString(flags).toUpperCase());
2336 return requestAudioFocus(l, requestAttributes, durationHint,
2337 flags & AUDIOFOCUS_FLAGS_APPS,
2338 null /* no AudioPolicy*/);
2343 * Request or lock audio focus.
2344 * This method is to be used by system components that have registered an
2345 * {@link android.media.audiopolicy.AudioPolicy} to request audio focus, but also to "lock" it
2346 * so focus granting is temporarily disabled.
2347 * @param l see the description of the same parameter in
2348 * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2349 * @param requestAttributes non null {@link AudioAttributes} describing the main reason for
2350 * requesting audio focus.
2351 * @param durationHint see the description of the same parameter in
2352 * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2353 * @param flags 0 or a combination of {link #AUDIOFOCUS_FLAG_DELAY_OK},
2354 * {@link #AUDIOFOCUS_FLAG_PAUSES_ON_DUCKABLE_LOSS}, and {@link #AUDIOFOCUS_FLAG_LOCK}.
2355 * <br>Use 0 when not using any flags for the request, which behaves like
2356 * {@link #requestAudioFocus(OnAudioFocusChangeListener, int, int)}, where either audio
2357 * focus is granted immediately, or the grant request fails because the system is in a
2358 * state where focus cannot change (e.g. a phone call).
2359 * @param ap a registered {@link android.media.audiopolicy.AudioPolicy} instance when locking
2361 * @return see the description of the same return value in
2362 * {@link #requestAudioFocus(OnAudioFocusChangeListener, AudioAttributes, int, int)}
2363 * @throws IllegalArgumentException
2366 public int requestAudioFocus(OnAudioFocusChangeListener l,
2367 @NonNull AudioAttributes requestAttributes,
2370 AudioPolicy ap) throws IllegalArgumentException {
2371 // parameter checking
2372 if (requestAttributes == null) {
2373 throw new IllegalArgumentException("Illegal null AudioAttributes argument");
2375 if ((durationHint < AUDIOFOCUS_GAIN) ||
2376 (durationHint > AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE)) {
2377 throw new IllegalArgumentException("Invalid duration hint");
2379 if (flags != (flags & AUDIOFOCUS_FLAGS_SYSTEM)) {
2380 throw new IllegalArgumentException("Illegal flags 0x"
2381 + Integer.toHexString(flags).toUpperCase());
2383 if (((flags & AUDIOFOCUS_FLAG_DELAY_OK) == AUDIOFOCUS_FLAG_DELAY_OK) && (l == null)) {
2384 throw new IllegalArgumentException(
2385 "Illegal null focus listener when flagged as accepting delayed focus grant");
2387 if (((flags & AUDIOFOCUS_FLAG_LOCK) == AUDIOFOCUS_FLAG_LOCK) && (ap == null)) {
2388 throw new IllegalArgumentException(
2389 "Illegal null audio policy when locking audio focus");
2392 int status = AUDIOFOCUS_REQUEST_FAILED;
2393 registerAudioFocusListener(l);
2394 IAudioService service = getService();
2396 status = service.requestAudioFocus(requestAttributes, durationHint, mICallBack,
2397 mAudioFocusDispatcher, getIdForAudioFocusListener(l),
2398 getContext().getOpPackageName() /* package name */, flags,
2399 ap != null ? ap.cb() : null);
2400 } catch (RemoteException e) {
2401 Log.e(TAG, "Can't call requestAudioFocus() on AudioService:", e);
2408 * Used internally by telephony package to request audio focus. Will cause the focus request
2409 * to be associated with the "voice communication" identifier only used in AudioService
2410 * to identify this use case.
2411 * @param streamType use STREAM_RING for focus requests when ringing, VOICE_CALL for
2412 * the establishment of the call
2413 * @param durationHint the type of focus request. AUDIOFOCUS_GAIN_TRANSIENT is recommended so
2414 * media applications resume after a call
2416 public void requestAudioFocusForCall(int streamType, int durationHint) {
2417 IAudioService service = getService();
2419 service.requestAudioFocus(new AudioAttributes.Builder()
2420 .setInternalLegacyStreamType(streamType).build(),
2421 durationHint, mICallBack, null,
2422 AudioSystem.IN_VOICE_COMM_FOCUS_ID,
2423 getContext().getOpPackageName(),
2424 AUDIOFOCUS_FLAG_LOCK,
2425 null /* policy token */);
2426 } catch (RemoteException e) {
2427 Log.e(TAG, "Can't call requestAudioFocusForCall() on AudioService:", e);
2433 * Used internally by telephony package to abandon audio focus, typically after a call or
2434 * when ringing ends and the call is rejected or not answered.
2435 * Should match one or more calls to {@link #requestAudioFocusForCall(int, int)}.
2437 public void abandonAudioFocusForCall() {
2438 IAudioService service = getService();
2440 service.abandonAudioFocus(null, AudioSystem.IN_VOICE_COMM_FOCUS_ID,
2441 null /*AudioAttributes, legacy behavior*/);
2442 } catch (RemoteException e) {
2443 Log.e(TAG, "Can't call abandonAudioFocusForCall() on AudioService:", e);
2448 * Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
2449 * @param l the listener with which focus was requested.
2450 * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
2452 public int abandonAudioFocus(OnAudioFocusChangeListener l) {
2453 return abandonAudioFocus(l, null /*AudioAttributes, legacy behavior*/);
2458 * Abandon audio focus. Causes the previous focus owner, if any, to receive focus.
2459 * @param l the listener with which focus was requested.
2460 * @param aa the {@link AudioAttributes} with which audio focus was requested
2461 * @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}
2464 public int abandonAudioFocus(OnAudioFocusChangeListener l, AudioAttributes aa) {
2465 int status = AUDIOFOCUS_REQUEST_FAILED;
2466 unregisterAudioFocusListener(l);
2467 IAudioService service = getService();
2469 status = service.abandonAudioFocus(mAudioFocusDispatcher,
2470 getIdForAudioFocusListener(l), aa);
2471 } catch (RemoteException e) {
2472 Log.e(TAG, "Can't call abandonAudioFocus() on AudioService:", e);
2477 //====================================================================
2480 * Register a component to be the sole receiver of MEDIA_BUTTON intents.
2481 * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
2482 * that will receive the media button intent. This broadcast receiver must be declared
2483 * in the application manifest. The package of the component must match that of
2484 * the context you're registering from.
2485 * @deprecated Use {@link MediaSession#setMediaButtonReceiver(PendingIntent)} instead.
2488 public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
2489 if (eventReceiver == null) {
2492 if (!eventReceiver.getPackageName().equals(getContext().getPackageName())) {
2493 Log.e(TAG, "registerMediaButtonEventReceiver() error: " +
2494 "receiver and context package names don't match");
2497 // construct a PendingIntent for the media button and register it
2498 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2499 // the associated intent will be handled by the component being registered
2500 mediaButtonIntent.setComponent(eventReceiver);
2501 PendingIntent pi = PendingIntent.getBroadcast(getContext(),
2502 0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
2503 registerMediaButtonIntent(pi, eventReceiver);
2507 * Register a component to be the sole receiver of MEDIA_BUTTON intents. This is like
2508 * {@link #registerMediaButtonEventReceiver(android.content.ComponentName)}, but allows
2509 * the buttons to go to any PendingIntent. Note that you should only use this form if
2510 * you know you will continue running for the full time until unregistering the
2512 * @param eventReceiver target that will receive media button intents. The PendingIntent
2513 * will be sent an {@link Intent#ACTION_MEDIA_BUTTON} event when a media button action
2514 * occurs, with {@link Intent#EXTRA_KEY_EVENT} added and holding the key code of the
2515 * media button that was pressed.
2516 * @deprecated Use {@link MediaSession#setMediaButtonReceiver(PendingIntent)} instead.
2519 public void registerMediaButtonEventReceiver(PendingIntent eventReceiver) {
2520 if (eventReceiver == null) {
2523 registerMediaButtonIntent(eventReceiver, null);
2528 * no-op if (pi == null) or (eventReceiver == null)
2530 public void registerMediaButtonIntent(PendingIntent pi, ComponentName eventReceiver) {
2532 Log.e(TAG, "Cannot call registerMediaButtonIntent() with a null parameter");
2535 MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
2536 helper.addMediaButtonListener(pi, eventReceiver, getContext());
2540 * Unregister the receiver of MEDIA_BUTTON intents.
2541 * @param eventReceiver identifier of a {@link android.content.BroadcastReceiver}
2542 * that was registered with {@link #registerMediaButtonEventReceiver(ComponentName)}.
2543 * @deprecated Use {@link MediaSession} instead.
2546 public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
2547 if (eventReceiver == null) {
2550 // construct a PendingIntent for the media button and unregister it
2551 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2552 // the associated intent will be handled by the component being registered
2553 mediaButtonIntent.setComponent(eventReceiver);
2554 PendingIntent pi = PendingIntent.getBroadcast(getContext(),
2555 0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/);
2556 unregisterMediaButtonIntent(pi);
2560 * Unregister the receiver of MEDIA_BUTTON intents.
2561 * @param eventReceiver same PendingIntent that was registed with
2562 * {@link #registerMediaButtonEventReceiver(PendingIntent)}.
2563 * @deprecated Use {@link MediaSession} instead.
2566 public void unregisterMediaButtonEventReceiver(PendingIntent eventReceiver) {
2567 if (eventReceiver == null) {
2570 unregisterMediaButtonIntent(eventReceiver);
2576 public void unregisterMediaButtonIntent(PendingIntent pi) {
2577 MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
2578 helper.removeMediaButtonListener(pi);
2582 * Registers the remote control client for providing information to display on the remote
2584 * @param rcClient The remote control client from which remote controls will receive
2585 * information to display.
2586 * @see RemoteControlClient
2587 * @deprecated Use {@link MediaSession} instead.
2590 public void registerRemoteControlClient(RemoteControlClient rcClient) {
2591 if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
2594 rcClient.registerWithSession(MediaSessionLegacyHelper.getHelper(getContext()));
2598 * Unregisters the remote control client that was providing information to display on the
2600 * @param rcClient The remote control client to unregister.
2601 * @see #registerRemoteControlClient(RemoteControlClient)
2602 * @deprecated Use {@link MediaSession} instead.
2605 public void unregisterRemoteControlClient(RemoteControlClient rcClient) {
2606 if ((rcClient == null) || (rcClient.getRcMediaIntent() == null)) {
2609 rcClient.unregisterWithSession(MediaSessionLegacyHelper.getHelper(getContext()));
2613 * Registers a {@link RemoteController} instance for it to receive media
2614 * metadata updates and playback state information from applications using
2615 * {@link RemoteControlClient}, and control their playback.
2617 * Registration requires the {@link RemoteController.OnClientUpdateListener} listener to be
2618 * one of the enabled notification listeners (see
2619 * {@link android.service.notification.NotificationListenerService}).
2621 * @param rctlr the object to register.
2622 * @return true if the {@link RemoteController} was successfully registered,
2623 * false if an error occurred, due to an internal system error, or
2624 * insufficient permissions.
2626 * {@link MediaSessionManager#addOnActiveSessionsChangedListener(android.media.session.MediaSessionManager.OnActiveSessionsChangedListener, ComponentName)}
2627 * and {@link MediaController} instead.
2630 public boolean registerRemoteController(RemoteController rctlr) {
2631 if (rctlr == null) {
2634 rctlr.startListeningToSessions();
2639 * Unregisters a {@link RemoteController}, causing it to no longer receive
2640 * media metadata and playback state information, and no longer be capable
2641 * of controlling playback.
2643 * @param rctlr the object to unregister.
2645 * {@link MediaSessionManager#removeOnActiveSessionsChangedListener(android.media.session.MediaSessionManager.OnActiveSessionsChangedListener)}
2649 public void unregisterRemoteController(RemoteController rctlr) {
2650 if (rctlr == null) {
2653 rctlr.stopListeningToSessions();
2658 * Registers a remote control display that will be sent information by remote control clients.
2659 * Use this method if your IRemoteControlDisplay is not going to display artwork, otherwise
2660 * use {@link #registerRemoteControlDisplay(IRemoteControlDisplay, int, int)} to pass the
2661 * artwork size directly, or
2662 * {@link #remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay, int, int)} later if artwork
2663 * is not yet needed.
2664 * <p>Registration requires the {@link Manifest.permission#MEDIA_CONTENT_CONTROL} permission.
2665 * @param rcd the IRemoteControlDisplay
2667 public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) {
2668 // passing a negative value for art work width and height as they are unknown at this stage
2669 registerRemoteControlDisplay(rcd, /*w*/-1, /*h*/ -1);
2674 * Registers a remote control display that will be sent information by remote control clients.
2675 * <p>Registration requires the {@link Manifest.permission#MEDIA_CONTENT_CONTROL} permission.
2677 * @param w the maximum width of the expected bitmap. Negative values indicate it is
2678 * useless to send artwork.
2679 * @param h the maximum height of the expected bitmap. Negative values indicate it is
2680 * useless to send artwork.
2682 public void registerRemoteControlDisplay(IRemoteControlDisplay rcd, int w, int h) {
2686 IAudioService service = getService();
2688 service.registerRemoteControlDisplay(rcd, w, h);
2689 } catch (RemoteException e) {
2690 Log.e(TAG, "Dead object in registerRemoteControlDisplay " + e);
2696 * Unregisters a remote control display that was sent information by remote control clients.
2699 public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) {
2703 IAudioService service = getService();
2705 service.unregisterRemoteControlDisplay(rcd);
2706 } catch (RemoteException e) {
2707 Log.e(TAG, "Dead object in unregisterRemoteControlDisplay " + e);
2713 * Sets the artwork size a remote control display expects when receiving bitmaps.
2715 * @param w the maximum width of the expected bitmap. Negative values indicate it is
2716 * useless to send artwork.
2717 * @param h the maximum height of the expected bitmap. Negative values indicate it is
2718 * useless to send artwork.
2720 public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) {
2724 IAudioService service = getService();
2726 service.remoteControlDisplayUsesBitmapSize(rcd, w, h);
2727 } catch (RemoteException e) {
2728 Log.e(TAG, "Dead object in remoteControlDisplayUsesBitmapSize " + e);
2734 * Controls whether a remote control display needs periodic checks of the RemoteControlClient
2735 * playback position to verify that the estimated position has not drifted from the actual
2736 * position. By default the check is not performed.
2737 * The IRemoteControlDisplay must have been previously registered for this to have any effect.
2738 * @param rcd the IRemoteControlDisplay for which the anti-drift mechanism will be enabled
2739 * or disabled. No effect is null.
2740 * @param wantsSync if true, RemoteControlClient instances which expose their playback position
2741 * to the framework will regularly compare the estimated playback position with the actual
2742 * position, and will update the IRemoteControlDisplay implementation whenever a drift is
2745 public void remoteControlDisplayWantsPlaybackPositionSync(IRemoteControlDisplay rcd,
2746 boolean wantsSync) {
2750 IAudioService service = getService();
2752 service.remoteControlDisplayWantsPlaybackPositionSync(rcd, wantsSync);
2753 } catch (RemoteException e) {
2754 Log.e(TAG, "Dead object in remoteControlDisplayWantsPlaybackPositionSync " + e);
2760 * Register the given {@link AudioPolicy}.
2761 * This call is synchronous and blocks until the registration process successfully completed
2762 * or failed to complete.
2763 * @param policy the non-null {@link AudioPolicy} to register.
2764 * @return {@link #ERROR} if there was an error communicating with the registration service
2765 * or if the user doesn't have the required
2766 * {@link android.Manifest.permission#MODIFY_AUDIO_ROUTING} permission,
2767 * {@link #SUCCESS} otherwise.
2770 public int registerAudioPolicy(@NonNull AudioPolicy policy) {
2771 if (policy == null) {
2772 throw new IllegalArgumentException("Illegal null AudioPolicy argument");
2774 IAudioService service = getService();
2776 String regId = service.registerAudioPolicy(policy.getConfig(), policy.cb(),
2777 policy.hasFocusListener());
2778 if (regId == null) {
2781 policy.setRegistration(regId);
2783 // successful registration
2784 } catch (RemoteException e) {
2785 Log.e(TAG, "Dead object in registerAudioPolicyAsync()", e);
2793 * @param policy the non-null {@link AudioPolicy} to unregister.
2796 public void unregisterAudioPolicyAsync(@NonNull AudioPolicy policy) {
2797 if (policy == null) {
2798 throw new IllegalArgumentException("Illegal null AudioPolicy argument");
2800 IAudioService service = getService();
2802 service.unregisterAudioPolicyAsync(policy.cb());
2803 policy.setRegistration(null);
2804 } catch (RemoteException e) {
2805 Log.e(TAG, "Dead object in unregisterAudioPolicyAsync()", e);
2812 * Reload audio settings. This method is called by Settings backup
2813 * agent when audio settings are restored and causes the AudioService
2814 * to read and apply restored settings.
2816 public void reloadAudioSettings() {
2817 IAudioService service = getService();
2819 service.reloadAudioSettings();
2820 } catch (RemoteException e) {
2821 Log.e(TAG, "Dead object in reloadAudioSettings"+e);
2827 * Notifies AudioService that it is connected to an A2DP device that supports absolute volume,
2828 * so that AudioService can send volume change events to the A2DP device, rather than handling
2831 public void avrcpSupportsAbsoluteVolume(String address, boolean support) {
2832 IAudioService service = getService();
2834 service.avrcpSupportsAbsoluteVolume(address, support);
2835 } catch (RemoteException e) {
2836 Log.e(TAG, "Dead object in avrcpSupportsAbsoluteVolume", e);
2843 private final IBinder mICallBack = new Binder();
2846 * Checks whether the phone is in silent mode, with or without vibrate.
2848 * @return true if phone is in silent mode, with or without vibrate.
2850 * @see #getRingerMode()
2852 * @hide pending API Council approval
2854 public boolean isSilentMode() {
2855 int ringerMode = getRingerMode();
2856 boolean silentMode =
2857 (ringerMode == RINGER_MODE_SILENT) ||
2858 (ringerMode == RINGER_MODE_VIBRATE);
2862 // This section re-defines new output device constants from AudioSystem, because the AudioSystem
2863 // class is not used by other parts of the framework, which instead use definitions and methods
2864 // from AudioManager. AudioSystem is an internal class used by AudioManager and AudioService.
2867 * The audio device code for representing "no device." */
2868 public static final int DEVICE_NONE = AudioSystem.DEVICE_NONE;
2870 * The audio output device code for the small speaker at the front of the device used
2871 * when placing calls. Does not refer to an in-ear headphone without attached microphone,
2872 * such as earbuds, earphones, or in-ear monitors (IEM). Those would be handled as a
2873 * {@link #DEVICE_OUT_WIRED_HEADPHONE}.
2875 public static final int DEVICE_OUT_EARPIECE = AudioSystem.DEVICE_OUT_EARPIECE;
2877 * The audio output device code for the built-in speaker */
2878 public static final int DEVICE_OUT_SPEAKER = AudioSystem.DEVICE_OUT_SPEAKER;
2880 * The audio output device code for a wired headset with attached microphone */
2881 public static final int DEVICE_OUT_WIRED_HEADSET = AudioSystem.DEVICE_OUT_WIRED_HEADSET;
2883 * The audio output device code for a wired headphone without attached microphone */
2884 public static final int DEVICE_OUT_WIRED_HEADPHONE = AudioSystem.DEVICE_OUT_WIRED_HEADPHONE;
2886 * The audio output device code for generic Bluetooth SCO, for voice */
2887 public static final int DEVICE_OUT_BLUETOOTH_SCO = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
2889 * The audio output device code for Bluetooth SCO Headset Profile (HSP) and
2890 * Hands-Free Profile (HFP), for voice
2892 public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET =
2893 AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2895 * The audio output device code for Bluetooth SCO car audio, for voice */
2896 public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT =
2897 AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2899 * The audio output device code for generic Bluetooth A2DP, for music */
2900 public static final int DEVICE_OUT_BLUETOOTH_A2DP = AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP;
2902 * The audio output device code for Bluetooth A2DP headphones, for music */
2903 public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES =
2904 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2906 * The audio output device code for Bluetooth A2DP external speaker, for music */
2907 public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER =
2908 AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2910 * The audio output device code for S/PDIF (legacy) or HDMI
2911 * Deprecated: replaced by {@link #DEVICE_OUT_HDMI} */
2912 public static final int DEVICE_OUT_AUX_DIGITAL = AudioSystem.DEVICE_OUT_AUX_DIGITAL;
2914 * The audio output device code for HDMI */
2915 public static final int DEVICE_OUT_HDMI = AudioSystem.DEVICE_OUT_HDMI;
2917 * The audio output device code for an analog wired headset attached via a
2920 public static final int DEVICE_OUT_ANLG_DOCK_HEADSET = AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET;
2922 * The audio output device code for a digital wired headset attached via a
2925 public static final int DEVICE_OUT_DGTL_DOCK_HEADSET = AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET;
2927 * The audio output device code for a USB audio accessory. The accessory is in USB host
2928 * mode and the Android device in USB device mode
2930 public static final int DEVICE_OUT_USB_ACCESSORY = AudioSystem.DEVICE_OUT_USB_ACCESSORY;
2932 * The audio output device code for a USB audio device. The device is in USB device
2933 * mode and the Android device in USB host mode
2935 public static final int DEVICE_OUT_USB_DEVICE = AudioSystem.DEVICE_OUT_USB_DEVICE;
2937 * The audio output device code for projection output.
2939 public static final int DEVICE_OUT_REMOTE_SUBMIX = AudioSystem.DEVICE_OUT_REMOTE_SUBMIX;
2941 * The audio output device code the telephony voice TX path.
2943 public static final int DEVICE_OUT_TELEPHONY_TX = AudioSystem.DEVICE_OUT_TELEPHONY_TX;
2945 * The audio output device code for an analog jack with line impedance detected.
2947 public static final int DEVICE_OUT_LINE = AudioSystem.DEVICE_OUT_LINE;
2949 * The audio output device code for HDMI Audio Return Channel.
2951 public static final int DEVICE_OUT_HDMI_ARC = AudioSystem.DEVICE_OUT_HDMI_ARC;
2953 * The audio output device code for S/PDIF digital connection.
2955 public static final int DEVICE_OUT_SPDIF = AudioSystem.DEVICE_OUT_SPDIF;
2957 * The audio output device code for built-in FM transmitter.
2959 public static final int DEVICE_OUT_FM = AudioSystem.DEVICE_OUT_FM;
2961 * This is not used as a returned value from {@link #getDevicesForStream}, but could be
2962 * used in the future in a set method to select whatever default device is chosen by the
2963 * platform-specific implementation.
2965 public static final int DEVICE_OUT_DEFAULT = AudioSystem.DEVICE_OUT_DEFAULT;
2968 * The audio input device code for default built-in microphone
2970 public static final int DEVICE_IN_BUILTIN_MIC = AudioSystem.DEVICE_IN_BUILTIN_MIC;
2972 * The audio input device code for a Bluetooth SCO headset
2974 public static final int DEVICE_IN_BLUETOOTH_SCO_HEADSET =
2975 AudioSystem.DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2977 * The audio input device code for wired headset microphone
2979 public static final int DEVICE_IN_WIRED_HEADSET =
2980 AudioSystem.DEVICE_IN_WIRED_HEADSET;
2982 * The audio input device code for HDMI
2984 public static final int DEVICE_IN_HDMI =
2985 AudioSystem.DEVICE_IN_HDMI;
2987 * The audio input device code for telephony voice RX path
2989 public static final int DEVICE_IN_TELEPHONY_RX =
2990 AudioSystem.DEVICE_IN_TELEPHONY_RX;
2992 * The audio input device code for built-in microphone pointing to the back
2994 public static final int DEVICE_IN_BACK_MIC =
2995 AudioSystem.DEVICE_IN_BACK_MIC;
2997 * The audio input device code for analog from a docking station
2999 public static final int DEVICE_IN_ANLG_DOCK_HEADSET =
3000 AudioSystem.DEVICE_IN_ANLG_DOCK_HEADSET;
3002 * The audio input device code for digital from a docking station
3004 public static final int DEVICE_IN_DGTL_DOCK_HEADSET =
3005 AudioSystem.DEVICE_IN_DGTL_DOCK_HEADSET;
3007 * The audio input device code for a USB audio accessory. The accessory is in USB host
3008 * mode and the Android device in USB device mode
3010 public static final int DEVICE_IN_USB_ACCESSORY =
3011 AudioSystem.DEVICE_IN_USB_ACCESSORY;
3013 * The audio input device code for a USB audio device. The device is in USB device
3014 * mode and the Android device in USB host mode
3016 public static final int DEVICE_IN_USB_DEVICE =
3017 AudioSystem.DEVICE_IN_USB_DEVICE;
3019 * The audio input device code for a FM radio tuner
3021 public static final int DEVICE_IN_FM_TUNER = AudioSystem.DEVICE_IN_FM_TUNER;
3023 * The audio input device code for a TV tuner
3025 public static final int DEVICE_IN_TV_TUNER = AudioSystem.DEVICE_IN_TV_TUNER;
3027 * The audio input device code for an analog jack with line impedance detected
3029 public static final int DEVICE_IN_LINE = AudioSystem.DEVICE_IN_LINE;
3031 * The audio input device code for a S/PDIF digital connection
3033 public static final int DEVICE_IN_SPDIF = AudioSystem.DEVICE_IN_SPDIF;
3035 * The audio input device code for audio loopback
3037 public static final int DEVICE_IN_LOOPBACK = AudioSystem.DEVICE_IN_LOOPBACK;
3040 * Return true if the device code corresponds to an output device.
3043 public static boolean isOutputDevice(int device)
3045 return (device & AudioSystem.DEVICE_BIT_IN) == 0;
3049 * Return true if the device code corresponds to an input device.
3052 public static boolean isInputDevice(int device)
3054 return (device & AudioSystem.DEVICE_BIT_IN) == AudioSystem.DEVICE_BIT_IN;
3059 * Return the enabled devices for the specified output stream type.
3061 * @param streamType The stream type to query. One of
3062 * {@link #STREAM_VOICE_CALL},
3063 * {@link #STREAM_SYSTEM},
3064 * {@link #STREAM_RING},
3065 * {@link #STREAM_MUSIC},
3066 * {@link #STREAM_ALARM},
3067 * {@link #STREAM_NOTIFICATION},
3068 * {@link #STREAM_DTMF}.
3070 * @return The bit-mask "or" of audio output device codes for all enabled devices on this
3071 * stream. Zero or more of
3072 * {@link #DEVICE_OUT_EARPIECE},
3073 * {@link #DEVICE_OUT_SPEAKER},
3074 * {@link #DEVICE_OUT_WIRED_HEADSET},
3075 * {@link #DEVICE_OUT_WIRED_HEADPHONE},
3076 * {@link #DEVICE_OUT_BLUETOOTH_SCO},
3077 * {@link #DEVICE_OUT_BLUETOOTH_SCO_HEADSET},
3078 * {@link #DEVICE_OUT_BLUETOOTH_SCO_CARKIT},
3079 * {@link #DEVICE_OUT_BLUETOOTH_A2DP},
3080 * {@link #DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES},
3081 * {@link #DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER},
3082 * {@link #DEVICE_OUT_HDMI},
3083 * {@link #DEVICE_OUT_ANLG_DOCK_HEADSET},
3084 * {@link #DEVICE_OUT_DGTL_DOCK_HEADSET}.
3085 * {@link #DEVICE_OUT_USB_ACCESSORY}.
3086 * {@link #DEVICE_OUT_USB_DEVICE}.
3087 * {@link #DEVICE_OUT_REMOTE_SUBMIX}.
3088 * {@link #DEVICE_OUT_TELEPHONY_TX}.
3089 * {@link #DEVICE_OUT_LINE}.
3090 * {@link #DEVICE_OUT_HDMI_ARC}.
3091 * {@link #DEVICE_OUT_SPDIF}.
3092 * {@link #DEVICE_OUT_FM}.
3093 * {@link #DEVICE_OUT_DEFAULT} is not used here.
3095 * The implementation may support additional device codes beyond those listed, so
3096 * the application should ignore any bits which it does not recognize.
3097 * Note that the information may be imprecise when the implementation
3098 * cannot distinguish whether a particular device is enabled.
3102 public int getDevicesForStream(int streamType) {
3103 switch (streamType) {
3104 case STREAM_VOICE_CALL:
3109 case STREAM_NOTIFICATION:
3111 return AudioSystem.getDevicesForStream(streamType);
3118 * Indicate wired accessory connection state change.
3119 * @param device type of device connected/disconnected (AudioManager.DEVICE_OUT_xxx)
3120 * @param state new connection state: 1 connected, 0 disconnected
3121 * @param name device name
3124 public void setWiredDeviceConnectionState(int type, int state, String address, String name) {
3125 IAudioService service = getService();
3127 service.setWiredDeviceConnectionState(type, state, address, name,
3128 mApplicationContext.getOpPackageName());
3129 } catch (RemoteException e) {
3130 Log.e(TAG, "Dead object in setWiredDeviceConnectionState "+e);
3135 * Indicate A2DP source or sink connection state change.
3136 * @param device Bluetooth device connected/disconnected
3137 * @param state new connection state (BluetoothProfile.STATE_xxx)
3138 * @param profile profile for the A2DP device
3139 * (either {@link android.bluetooth.BluetoothProfile.A2DP} or
3140 * {@link android.bluetooth.BluetoothProfile.A2DP_SINK})
3141 * @return a delay in ms that the caller should wait before broadcasting
3142 * BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED intent.
3145 public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state,
3147 IAudioService service = getService();
3150 delay = service.setBluetoothA2dpDeviceConnectionState(device, state, profile);
3151 } catch (RemoteException e) {
3152 Log.e(TAG, "Dead object in setBluetoothA2dpDeviceConnectionState "+e);
3158 public IRingtonePlayer getRingtonePlayer() {
3160 return getService().getRingtonePlayer();
3161 } catch (RemoteException e) {
3167 * Used as a key for {@link #getProperty} to request the native or optimal output sample rate
3168 * for this device's primary output stream, in decimal Hz.
3170 public static final String PROPERTY_OUTPUT_SAMPLE_RATE =
3171 "android.media.property.OUTPUT_SAMPLE_RATE";
3174 * Used as a key for {@link #getProperty} to request the native or optimal output buffer size
3175 * for this device's primary output stream, in decimal PCM frames.
3177 public static final String PROPERTY_OUTPUT_FRAMES_PER_BUFFER =
3178 "android.media.property.OUTPUT_FRAMES_PER_BUFFER";
3181 * Used as a key for {@link #getProperty} to determine if the default microphone audio source
3182 * supports near-ultrasound frequencies (range of 18 - 21 kHz).
3184 public static final String PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND =
3185 "android.media.property.SUPPORT_MIC_NEAR_ULTRASOUND";
3188 * Used as a key for {@link #getProperty} to determine if the default speaker audio path
3189 * supports near-ultrasound frequencies (range of 18 - 21 kHz).
3191 public static final String PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND =
3192 "android.media.property.SUPPORT_SPEAKER_NEAR_ULTRASOUND";
3195 * Returns the value of the property with the specified key.
3196 * @param key One of the strings corresponding to a property key: either
3197 * {@link #PROPERTY_OUTPUT_SAMPLE_RATE} or
3198 * {@link #PROPERTY_OUTPUT_FRAMES_PER_BUFFER}
3199 * @return A string representing the associated value for that property key,
3200 * or null if there is no value for that key.
3202 public String getProperty(String key) {
3203 if (PROPERTY_OUTPUT_SAMPLE_RATE.equals(key)) {
3204 int outputSampleRate = AudioSystem.getPrimaryOutputSamplingRate();
3205 return outputSampleRate > 0 ? Integer.toString(outputSampleRate) : null;
3206 } else if (PROPERTY_OUTPUT_FRAMES_PER_BUFFER.equals(key)) {
3207 int outputFramesPerBuffer = AudioSystem.getPrimaryOutputFrameCount();
3208 return outputFramesPerBuffer > 0 ? Integer.toString(outputFramesPerBuffer) : null;
3209 } else if (PROPERTY_SUPPORT_MIC_NEAR_ULTRASOUND.equals(key)) {
3210 return SystemProperties.get(SYSTEM_PROPERTY_MIC_NEAR_ULTRASOUND,
3211 DEFAULT_RESULT_FALSE_STRING);
3212 } else if (PROPERTY_SUPPORT_SPEAKER_NEAR_ULTRASOUND.equals(key)) {
3213 return SystemProperties.get(SYSTEM_PROPERTY_SPEAKER_NEAR_ULTRASOUND,
3214 DEFAULT_RESULT_FALSE_STRING);
3216 // null or unknown key
3222 * Returns the estimated latency for the given stream type in milliseconds.
3224 * DO NOT UNHIDE. The existing approach for doing A/V sync has too many problems. We need
3225 * a better solution.
3228 public int getOutputLatency(int streamType) {
3229 return AudioSystem.getOutputLatency(streamType);
3233 * Registers a global volume controller interface. Currently limited to SystemUI.
3237 public void setVolumeController(IVolumeController controller) {
3239 getService().setVolumeController(controller);
3240 } catch (RemoteException e) {
3241 Log.w(TAG, "Error setting volume controller", e);
3246 * Notify audio manager about volume controller visibility changes.
3247 * Currently limited to SystemUI.
3251 public void notifyVolumeControllerVisible(IVolumeController controller, boolean visible) {
3253 getService().notifyVolumeControllerVisible(controller, visible);
3254 } catch (RemoteException e) {
3255 Log.w(TAG, "Error notifying about volume controller visibility", e);
3260 * Only useful for volume controllers.
3263 public boolean isStreamAffectedByRingerMode(int streamType) {
3265 return getService().isStreamAffectedByRingerMode(streamType);
3266 } catch (RemoteException e) {
3267 Log.w(TAG, "Error calling isStreamAffectedByRingerMode", e);
3273 * Only useful for volume controllers.
3276 public boolean isStreamAffectedByMute(int streamType) {
3278 return getService().isStreamAffectedByMute(streamType);
3279 } catch (RemoteException e) {
3280 Log.w(TAG, "Error calling isStreamAffectedByMute", e);
3286 * Only useful for volume controllers.
3289 public void disableSafeMediaVolume() {
3291 getService().disableSafeMediaVolume(mApplicationContext.getOpPackageName());
3292 } catch (RemoteException e) {
3293 Log.w(TAG, "Error disabling safe media volume", e);
3298 * Only useful for volume controllers.
3301 public void setRingerModeInternal(int ringerMode) {
3303 getService().setRingerModeInternal(ringerMode, getContext().getOpPackageName());
3304 } catch (RemoteException e) {
3305 Log.w(TAG, "Error calling setRingerModeInternal", e);
3310 * Only useful for volume controllers.
3313 public int getRingerModeInternal() {
3315 return getService().getRingerModeInternal();
3316 } catch (RemoteException e) {
3317 Log.w(TAG, "Error calling getRingerModeInternal", e);
3318 return RINGER_MODE_NORMAL;
3323 * Only useful for volume controllers.
3326 public void setVolumePolicy(VolumePolicy policy) {
3328 getService().setVolumePolicy(policy);
3329 } catch (RemoteException e) {
3330 Log.w(TAG, "Error calling setVolumePolicy", e);
3335 * Set Hdmi Cec system audio mode.
3337 * @param on whether to be on system audio mode
3338 * @return output device type. 0 (DEVICE_NONE) if failed to set device.
3341 public int setHdmiSystemAudioSupported(boolean on) {
3343 return getService().setHdmiSystemAudioSupported(on);
3344 } catch (RemoteException e) {
3345 Log.w(TAG, "Error setting system audio mode", e);
3346 return AudioSystem.DEVICE_NONE;
3351 * Returns true if Hdmi Cec system audio mode is supported.
3356 public boolean isHdmiSystemAudioSupported() {
3358 return getService().isHdmiSystemAudioSupported();
3359 } catch (RemoteException e) {
3360 Log.w(TAG, "Error querying system audio mode", e);
3366 * Return codes for listAudioPorts(), createAudioPatch() ...
3370 * CANDIDATE FOR PUBLIC API
3372 public static final int SUCCESS = AudioSystem.SUCCESS;
3374 * A default error code.
3376 public static final int ERROR = AudioSystem.ERROR;
3378 * CANDIDATE FOR PUBLIC API
3380 public static final int ERROR_BAD_VALUE = AudioSystem.BAD_VALUE;
3383 public static final int ERROR_INVALID_OPERATION = AudioSystem.INVALID_OPERATION;
3386 public static final int ERROR_PERMISSION_DENIED = AudioSystem.PERMISSION_DENIED;
3389 public static final int ERROR_NO_INIT = AudioSystem.NO_INIT;
3391 * An error code indicating that the object reporting it is no longer valid and needs to
3394 public static final int ERROR_DEAD_OBJECT = AudioSystem.DEAD_OBJECT;
3397 * Returns a list of descriptors for all audio ports managed by the audio framework.
3398 * Audio ports are nodes in the audio framework or audio hardware that can be configured
3399 * or connected and disconnected with createAudioPatch() or releaseAudioPatch().
3400 * See AudioPort for a list of attributes of each audio port.
3401 * @param ports An AudioPort ArrayList where the list will be returned.
3404 public int listAudioPorts(ArrayList<AudioPort> ports) {
3405 return updateAudioPortCache(ports, null);
3409 * Specialized version of listAudioPorts() listing only audio devices (AudioDevicePort)
3410 * @see listAudioPorts(ArrayList<AudioPort>)
3413 public int listAudioDevicePorts(ArrayList<AudioDevicePort> devices) {
3414 ArrayList<AudioPort> ports = new ArrayList<AudioPort>();
3415 int status = updateAudioPortCache(ports, null);
3416 if (status == SUCCESS) {
3418 for (int i = 0; i < ports.size(); i++) {
3419 if (ports.get(i) instanceof AudioDevicePort) {
3420 devices.add((AudioDevicePort)ports.get(i));
3428 * Create a connection between two or more devices. The framework will reject the request if
3429 * device types are not compatible or the implementation does not support the requested
3431 * NOTE: current implementation is limited to one source and one sink per patch.
3432 * @param patch AudioPatch array where the newly created patch will be returned.
3433 * As input, if patch[0] is not null, the specified patch will be replaced by the
3434 * new patch created. This avoids calling releaseAudioPatch() when modifying a
3435 * patch and allows the implementation to optimize transitions.
3436 * @param sources List of source audio ports. All must be AudioPort.ROLE_SOURCE.
3437 * @param sinks List of sink audio ports. All must be AudioPort.ROLE_SINK.
3439 * @return - {@link #SUCCESS} if connection is successful.
3440 * - {@link #ERROR_BAD_VALUE} if incompatible device types are passed.
3441 * - {@link #ERROR_INVALID_OPERATION} if the requested connection is not supported.
3442 * - {@link #ERROR_PERMISSION_DENIED} if the client does not have permission to create
3444 * - {@link #ERROR_DEAD_OBJECT} if the server process is dead
3445 * - {@link #ERROR} if patch cannot be connected for any other reason.
3447 * patch[0] contains the newly created patch
3450 public int createAudioPatch(AudioPatch[] patch,
3451 AudioPortConfig[] sources,
3452 AudioPortConfig[] sinks) {
3453 return AudioSystem.createAudioPatch(patch, sources, sinks);
3457 * Releases an existing audio patch connection.
3458 * @param patch The audio patch to disconnect.
3459 * @return - {@link #SUCCESS} if disconnection is successful.
3460 * - {@link #ERROR_BAD_VALUE} if the specified patch does not exist.
3461 * - {@link #ERROR_PERMISSION_DENIED} if the client does not have permission to release
3463 * - {@link #ERROR_DEAD_OBJECT} if the server process is dead
3464 * - {@link #ERROR} if patch cannot be released for any other reason.
3467 public int releaseAudioPatch(AudioPatch patch) {
3468 return AudioSystem.releaseAudioPatch(patch);
3472 * List all existing connections between audio ports.
3473 * @param patches An AudioPatch array where the list will be returned.
3476 public int listAudioPatches(ArrayList<AudioPatch> patches) {
3477 return updateAudioPortCache(null, patches);
3481 * Set the gain on the specified AudioPort. The AudioGainConfig config is build by
3482 * AudioGain.buildConfig()
3485 public int setAudioPortGain(AudioPort port, AudioGainConfig gain) {
3486 if (port == null || gain == null) {
3487 return ERROR_BAD_VALUE;
3489 AudioPortConfig activeConfig = port.activeConfig();
3490 AudioPortConfig config = new AudioPortConfig(port, activeConfig.samplingRate(),
3491 activeConfig.channelMask(), activeConfig.format(), gain);
3492 config.mConfigMask = AudioPortConfig.GAIN;
3493 return AudioSystem.setAudioPortConfig(config);
3497 * Listener registered by client to be notified upon new audio port connections,
3498 * disconnections or attributes update.
3501 public interface OnAudioPortUpdateListener {
3503 * Callback method called upon audio port list update.
3504 * @param portList the updated list of audio ports
3506 public void onAudioPortListUpdate(AudioPort[] portList);
3509 * Callback method called upon audio patch list update.
3510 * @param patchList the updated list of audio patches
3512 public void onAudioPatchListUpdate(AudioPatch[] patchList);
3515 * Callback method called when the mediaserver dies
3517 public void onServiceDied();
3521 * Register an audio port list update listener.
3524 public void registerAudioPortUpdateListener(OnAudioPortUpdateListener l) {
3525 sAudioPortEventHandler.registerListener(l);
3529 * Unregister an audio port list update listener.
3532 public void unregisterAudioPortUpdateListener(OnAudioPortUpdateListener l) {
3533 sAudioPortEventHandler.unregisterListener(l);
3537 // AudioPort implementation
3540 static final int AUDIOPORT_GENERATION_INIT = 0;
3541 static Integer sAudioPortGeneration = new Integer(AUDIOPORT_GENERATION_INIT);
3542 static ArrayList<AudioPort> sAudioPortsCached = new ArrayList<AudioPort>();
3543 static ArrayList<AudioPatch> sAudioPatchesCached = new ArrayList<AudioPatch>();
3545 static int resetAudioPortGeneration() {
3547 synchronized (sAudioPortGeneration) {
3548 generation = sAudioPortGeneration;
3549 sAudioPortGeneration = AUDIOPORT_GENERATION_INIT;
3554 static int updateAudioPortCache(ArrayList<AudioPort> ports, ArrayList<AudioPatch> patches) {
3555 synchronized (sAudioPortGeneration) {
3557 if (sAudioPortGeneration == AUDIOPORT_GENERATION_INIT) {
3558 int[] patchGeneration = new int[1];
3559 int[] portGeneration = new int[1];
3561 ArrayList<AudioPort> newPorts = new ArrayList<AudioPort>();
3562 ArrayList<AudioPatch> newPatches = new ArrayList<AudioPatch>();
3566 status = AudioSystem.listAudioPorts(newPorts, portGeneration);
3567 if (status != SUCCESS) {
3568 Log.w(TAG, "updateAudioPortCache: listAudioPorts failed");
3572 status = AudioSystem.listAudioPatches(newPatches, patchGeneration);
3573 if (status != SUCCESS) {
3574 Log.w(TAG, "updateAudioPortCache: listAudioPatches failed");
3577 } while (patchGeneration[0] != portGeneration[0]);
3579 for (int i = 0; i < newPatches.size(); i++) {
3580 for (int j = 0; j < newPatches.get(i).sources().length; j++) {
3581 AudioPortConfig portCfg = updatePortConfig(newPatches.get(i).sources()[j],
3583 newPatches.get(i).sources()[j] = portCfg;
3585 for (int j = 0; j < newPatches.get(i).sinks().length; j++) {
3586 AudioPortConfig portCfg = updatePortConfig(newPatches.get(i).sinks()[j],
3588 newPatches.get(i).sinks()[j] = portCfg;
3591 for (Iterator<AudioPatch> i = newPatches.iterator(); i.hasNext(); ) {
3592 AudioPatch newPatch = i.next();
3593 boolean hasInvalidPort = false;
3594 for (AudioPortConfig portCfg : newPatch.sources()) {
3595 if (portCfg == null) {
3596 hasInvalidPort = true;
3600 for (AudioPortConfig portCfg : newPatch.sinks()) {
3601 if (portCfg == null) {
3602 hasInvalidPort = true;
3606 if (hasInvalidPort) {
3607 // Temporarily remove patches with invalid ports. One who created the patch
3608 // is responsible for dealing with the port change.
3613 sAudioPortsCached = newPorts;
3614 sAudioPatchesCached = newPatches;
3615 sAudioPortGeneration = portGeneration[0];
3617 if (ports != null) {
3619 ports.addAll(sAudioPortsCached);
3621 if (patches != null) {
3623 patches.addAll(sAudioPatchesCached);
3629 static AudioPortConfig updatePortConfig(AudioPortConfig portCfg, ArrayList<AudioPort> ports) {
3630 AudioPort port = portCfg.port();
3632 for (k = 0; k < ports.size(); k++) {
3633 // compare handles because the port returned by JNI is not of the correct
3635 if (ports.get(k).handle().equals(port.handle())) {
3636 port = ports.get(k);
3640 if (k == ports.size()) {
3641 // this hould never happen
3642 Log.e(TAG, "updatePortConfig port not found for handle: "+port.handle().id());
3645 AudioGainConfig gainCfg = portCfg.gain();
3646 if (gainCfg != null) {
3647 AudioGain gain = port.gain(gainCfg.index());
3648 gainCfg = gain.buildConfig(gainCfg.mode(),
3649 gainCfg.channelMask(),
3651 gainCfg.rampDurationMs());
3653 return port.buildConfig(portCfg.samplingRate(),
3654 portCfg.channelMask(),