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