AudioService.java revision 8517e46f3d3c2ce11de09aa849a8533ffc1a2026
1/* 2 * Copyright (C) 2006 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 static android.media.AudioManager.RINGER_MODE_NORMAL; 20import static android.media.AudioManager.RINGER_MODE_SILENT; 21import static android.media.AudioManager.RINGER_MODE_VIBRATE; 22 23import android.app.ActivityManagerNative; 24import android.app.KeyguardManager; 25import android.app.PendingIntent; 26import android.app.PendingIntent.CanceledException; 27import android.bluetooth.BluetoothA2dp; 28import android.bluetooth.BluetoothAdapter; 29import android.bluetooth.BluetoothClass; 30import android.bluetooth.BluetoothDevice; 31import android.bluetooth.BluetoothHeadset; 32import android.bluetooth.BluetoothProfile; 33import android.content.BroadcastReceiver; 34import android.content.ComponentName; 35import android.content.ContentResolver; 36import android.content.Context; 37import android.content.Intent; 38import android.content.IntentFilter; 39import android.content.pm.PackageManager; 40import android.database.ContentObserver; 41import android.media.MediaPlayer.OnCompletionListener; 42import android.media.MediaPlayer.OnErrorListener; 43import android.os.Binder; 44import android.os.Bundle; 45import android.os.Environment; 46import android.os.Handler; 47import android.os.IBinder; 48import android.os.Looper; 49import android.os.Message; 50import android.os.RemoteException; 51import android.os.ServiceManager; 52import android.os.SystemProperties; 53import android.provider.Settings; 54import android.provider.Settings.System; 55import android.telephony.PhoneStateListener; 56import android.telephony.TelephonyManager; 57import android.util.Log; 58import android.view.KeyEvent; 59import android.view.VolumePanel; 60 61import com.android.internal.telephony.ITelephony; 62 63import java.io.FileDescriptor; 64import java.io.IOException; 65import java.io.PrintWriter; 66import java.util.ArrayList; 67import java.util.HashMap; 68import java.util.Iterator; 69import java.util.List; 70import java.util.Map; 71import java.util.NoSuchElementException; 72import java.util.Set; 73import java.util.Stack; 74 75/** 76 * The implementation of the volume manager service. 77 * <p> 78 * This implementation focuses on delivering a responsive UI. Most methods are 79 * asynchronous to external calls. For example, the task of setting a volume 80 * will update our internal state, but in a separate thread will set the system 81 * volume and later persist to the database. Similarly, setting the ringer mode 82 * will update the state and broadcast a change and in a separate thread later 83 * persist the ringer mode. 84 * 85 * @hide 86 */ 87public class AudioService extends IAudioService.Stub { 88 89 private static final String TAG = "AudioService"; 90 91 /** Debug remote control client/display feature */ 92 protected static final boolean DEBUG_RC = false; 93 94 /** How long to delay before persisting a change in volume/ringer mode. */ 95 private static final int PERSIST_DELAY = 3000; 96 97 private Context mContext; 98 private ContentResolver mContentResolver; 99 private boolean mVoiceCapable; 100 101 /** The UI */ 102 private VolumePanel mVolumePanel; 103 104 // sendMsg() flags 105 /** If the msg is already queued, replace it with this one. */ 106 private static final int SENDMSG_REPLACE = 0; 107 /** If the msg is already queued, ignore this one and leave the old. */ 108 private static final int SENDMSG_NOOP = 1; 109 /** If the msg is already queued, queue this one and leave the old. */ 110 private static final int SENDMSG_QUEUE = 2; 111 112 // AudioHandler message.whats 113 private static final int MSG_SET_DEVICE_VOLUME = 0; 114 private static final int MSG_PERSIST_VOLUME = 1; 115 private static final int MSG_PERSIST_RINGER_MODE = 3; 116 private static final int MSG_PERSIST_VIBRATE_SETTING = 4; 117 private static final int MSG_MEDIA_SERVER_DIED = 5; 118 private static final int MSG_MEDIA_SERVER_STARTED = 6; 119 private static final int MSG_PLAY_SOUND_EFFECT = 7; 120 private static final int MSG_BTA2DP_DOCK_TIMEOUT = 8; 121 private static final int MSG_LOAD_SOUND_EFFECTS = 9; 122 private static final int MSG_SET_FORCE_USE = 10; 123 private static final int MSG_PERSIST_MEDIABUTTONRECEIVER = 11; 124 private static final int MSG_BT_HEADSET_CNCT_FAILED = 12; 125 private static final int MSG_RCDISPLAY_CLEAR = 13; 126 private static final int MSG_RCDISPLAY_UPDATE = 14; 127 private static final int MSG_SET_ALL_VOLUMES = 15; 128 129 130 // flags for MSG_PERSIST_VOLUME indicating if current and/or last audible volume should be 131 // persisted 132 private static final int PERSIST_CURRENT = 0x1; 133 private static final int PERSIST_LAST_AUDIBLE = 0x2; 134 135 private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000; 136 // Timeout for connection to bluetooth headset service 137 private static final int BT_HEADSET_CNCT_TIMEOUT_MS = 3000; 138 139 // Amount to raise/lower master volume 140 // FIXME - this should probably be in a resource 141 private static final float MASTER_VOLUME_INCREMENT = 0.05f; 142 143 /** @see AudioSystemThread */ 144 private AudioSystemThread mAudioSystemThread; 145 /** @see AudioHandler */ 146 private AudioHandler mAudioHandler; 147 /** @see VolumeStreamState */ 148 private VolumeStreamState[] mStreamStates; 149 private SettingsObserver mSettingsObserver; 150 151 private int mMode; 152 // protects mRingerMode 153 private final Object mSettingsLock = new Object(); 154 private boolean mMediaServerOk; 155 156 private SoundPool mSoundPool; 157 private final Object mSoundEffectsLock = new Object(); 158 private static final int NUM_SOUNDPOOL_CHANNELS = 4; 159 private static final int SOUND_EFFECT_VOLUME = 1000; 160 161 /* Sound effect file names */ 162 private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/"; 163 private static final String[] SOUND_EFFECT_FILES = new String[] { 164 "Effect_Tick.ogg", 165 "KeypressStandard.ogg", 166 "KeypressSpacebar.ogg", 167 "KeypressDelete.ogg", 168 "KeypressReturn.ogg" 169 }; 170 171 /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to 172 * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect 173 * uses soundpool (second column) */ 174 private final int[][] SOUND_EFFECT_FILES_MAP = new int[][] { 175 {0, -1}, // FX_KEY_CLICK 176 {0, -1}, // FX_FOCUS_NAVIGATION_UP 177 {0, -1}, // FX_FOCUS_NAVIGATION_DOWN 178 {0, -1}, // FX_FOCUS_NAVIGATION_LEFT 179 {0, -1}, // FX_FOCUS_NAVIGATION_RIGHT 180 {1, -1}, // FX_KEYPRESS_STANDARD 181 {2, -1}, // FX_KEYPRESS_SPACEBAR 182 {3, -1}, // FX_FOCUS_DELETE 183 {4, -1} // FX_FOCUS_RETURN 184 }; 185 186 /** @hide Maximum volume index values for audio streams */ 187 private final int[] MAX_STREAM_VOLUME = new int[] { 188 5, // STREAM_VOICE_CALL 189 7, // STREAM_SYSTEM 190 7, // STREAM_RING 191 15, // STREAM_MUSIC 192 7, // STREAM_ALARM 193 7, // STREAM_NOTIFICATION 194 15, // STREAM_BLUETOOTH_SCO 195 7, // STREAM_SYSTEM_ENFORCED 196 15, // STREAM_DTMF 197 15 // STREAM_TTS 198 }; 199 /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings 200 * of another stream: This avoids multiplying the volume settings for hidden 201 * stream types that follow other stream behavior for volume settings 202 * NOTE: do not create loops in aliases! */ 203 private final int[] STREAM_VOLUME_ALIAS = new int[] { 204 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL 205 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM 206 AudioSystem.STREAM_RING, // STREAM_RING 207 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC 208 AudioSystem.STREAM_ALARM, // STREAM_ALARM 209 AudioSystem.STREAM_RING, // STREAM_NOTIFICATION 210 AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO 211 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM_ENFORCED 212 AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF 213 AudioSystem.STREAM_MUSIC // STREAM_TTS 214 }; 215 216 private final AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() { 217 public void onError(int error) { 218 switch (error) { 219 case AudioSystem.AUDIO_STATUS_SERVER_DIED: 220 if (mMediaServerOk) { 221 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0, 222 null, 1500); 223 mMediaServerOk = false; 224 } 225 break; 226 case AudioSystem.AUDIO_STATUS_OK: 227 if (!mMediaServerOk) { 228 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SENDMSG_NOOP, 0, 0, 229 null, 0); 230 mMediaServerOk = true; 231 } 232 break; 233 default: 234 break; 235 } 236 } 237 }; 238 239 /** 240 * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL}, 241 * {@link AudioManager#RINGER_MODE_SILENT}, or 242 * {@link AudioManager#RINGER_MODE_VIBRATE}. 243 */ 244 // protected by mSettingsLock 245 private int mRingerMode; 246 247 /** @see System#MODE_RINGER_STREAMS_AFFECTED */ 248 private int mRingerModeAffectedStreams; 249 250 // Streams currently muted by ringer mode 251 private int mRingerModeMutedStreams; 252 253 /** @see System#MUTE_STREAMS_AFFECTED */ 254 private int mMuteAffectedStreams; 255 256 /** 257 * Has multiple bits per vibrate type to indicate the type's vibrate 258 * setting. See {@link #setVibrateSetting(int, int)}. 259 * <p> 260 * NOTE: This is not the final decision of whether vibrate is on/off for the 261 * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}. 262 */ 263 private int mVibrateSetting; 264 265 // Broadcast receiver for device connections intent broadcasts 266 private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver(); 267 268 // Broadcast receiver for media button broadcasts (separate from mReceiver to 269 // independently change its priority) 270 private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver(); 271 272 // Used to alter media button redirection when the phone is ringing. 273 private boolean mIsRinging = false; 274 275 // Devices currently connected 276 private final HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>(); 277 278 // Forced device usage for communications 279 private int mForcedUseForComm; 280 281 // List of binder death handlers for setMode() client processes. 282 // The last process to have called setMode() is at the top of the list. 283 private final ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>(); 284 285 // List of clients having issued a SCO start request 286 private final ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>(); 287 288 // BluetoothHeadset API to control SCO connection 289 private BluetoothHeadset mBluetoothHeadset; 290 291 // Bluetooth headset device 292 private BluetoothDevice mBluetoothHeadsetDevice; 293 294 // Indicate if SCO audio connection is currently active and if the initiator is 295 // audio service (internal) or bluetooth headset (external) 296 private int mScoAudioState; 297 // SCO audio state is not active 298 private static final int SCO_STATE_INACTIVE = 0; 299 // SCO audio activation request waiting for headset service to connect 300 private static final int SCO_STATE_ACTIVATE_REQ = 1; 301 // SCO audio state is active or starting due to a local request to start a virtual call 302 private static final int SCO_STATE_ACTIVE_INTERNAL = 3; 303 // SCO audio deactivation request waiting for headset service to connect 304 private static final int SCO_STATE_DEACTIVATE_REQ = 5; 305 306 // SCO audio state is active due to an action in BT handsfree (either voice recognition or 307 // in call audio) 308 private static final int SCO_STATE_ACTIVE_EXTERNAL = 2; 309 // Deactivation request for all SCO connections (initiated by audio mode change) 310 // waiting for headset service to connect 311 private static final int SCO_STATE_DEACTIVATE_EXT_REQ = 4; 312 313 // Current connection state indicated by bluetooth headset 314 private int mScoConnectionState; 315 316 // true if boot sequence has been completed 317 private boolean mBootCompleted; 318 // listener for SoundPool sample load completion indication 319 private SoundPoolCallback mSoundPoolCallBack; 320 // thread for SoundPool listener 321 private SoundPoolListenerThread mSoundPoolListenerThread; 322 // message looper for SoundPool listener 323 private Looper mSoundPoolLooper = null; 324 // default volume applied to sound played with playSoundEffect() 325 private static final int SOUND_EFFECT_DEFAULT_VOLUME_DB = -20; 326 // volume applied to sound played with playSoundEffect() read from ro.config.sound_fx_volume 327 private int SOUND_EFFECT_VOLUME_DB; 328 // getActiveStreamType() will return STREAM_NOTIFICATION during this period after a notification 329 // stopped 330 private static final int NOTIFICATION_VOLUME_DELAY_MS = 5000; 331 // previous volume adjustment direction received by checkForRingerModeChange() 332 private int mPrevVolDirection = AudioManager.ADJUST_SAME; 333 // Keyguard manager proxy 334 private KeyguardManager mKeyguardManager; 335 336 337 /////////////////////////////////////////////////////////////////////////// 338 // Construction 339 /////////////////////////////////////////////////////////////////////////// 340 341 /** @hide */ 342 public AudioService(Context context) { 343 mContext = context; 344 mContentResolver = context.getContentResolver(); 345 mVoiceCapable = mContext.getResources().getBoolean( 346 com.android.internal.R.bool.config_voice_capable); 347 348 // Intialized volume 349 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt( 350 "ro.config.vc_call_vol_steps", 351 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]); 352 353 SOUND_EFFECT_VOLUME_DB = SystemProperties.getInt( 354 "ro.config.sound_fx_volume", 355 SOUND_EFFECT_DEFAULT_VOLUME_DB); 356 357 mVolumePanel = new VolumePanel(context, this); 358 mForcedUseForComm = AudioSystem.FORCE_NONE; 359 createAudioSystemThread(); 360 readPersistedSettings(); 361 mSettingsObserver = new SettingsObserver(); 362 createStreamStates(); 363 364 mMode = AudioSystem.MODE_NORMAL; 365 mMediaServerOk = true; 366 367 // Call setRingerModeInt() to apply correct mute 368 // state on streams affected by ringer mode. 369 mRingerModeMutedStreams = 0; 370 setRingerModeInt(getRingerMode(), false); 371 372 AudioSystem.setErrorCallback(mAudioSystemCallback); 373 374 // Register for device connection intent broadcasts. 375 IntentFilter intentFilter = 376 new IntentFilter(Intent.ACTION_HEADSET_PLUG); 377 378 intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); 379 intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); 380 intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); 381 intentFilter.addAction(Intent.ACTION_DOCK_EVENT); 382 intentFilter.addAction(Intent.ACTION_USB_ANLG_HEADSET_PLUG); 383 intentFilter.addAction(Intent.ACTION_USB_DGTL_HEADSET_PLUG); 384 intentFilter.addAction(Intent.ACTION_HDMI_AUDIO_PLUG); 385 intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED); 386 intentFilter.addAction(Intent.ACTION_SCREEN_ON); 387 intentFilter.addAction(Intent.ACTION_SCREEN_OFF); 388 context.registerReceiver(mReceiver, intentFilter); 389 390 // Register for package removal intent broadcasts for media button receiver persistence 391 IntentFilter pkgFilter = new IntentFilter(); 392 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 393 pkgFilter.addDataScheme("package"); 394 context.registerReceiver(mReceiver, pkgFilter); 395 396 // Register for media button intent broadcasts. 397 intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); 398 // Workaround for bug on priority setting 399 //intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 400 intentFilter.setPriority(Integer.MAX_VALUE); 401 context.registerReceiver(mMediaButtonReceiver, intentFilter); 402 403 // Register for phone state monitoring 404 TelephonyManager tmgr = (TelephonyManager) 405 context.getSystemService(Context.TELEPHONY_SERVICE); 406 tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 407 408 if (context.getResources().getBoolean( 409 com.android.internal.R.bool.config_useMasterVolume)) { 410 float volume = Settings.System.getFloat(mContentResolver, 411 Settings.System.VOLUME_MASTER, -1.0f); 412 if (volume >= 0.0f) { 413 AudioSystem.setMasterVolume(volume); 414 } 415 } 416 } 417 418 private void createAudioSystemThread() { 419 mAudioSystemThread = new AudioSystemThread(); 420 mAudioSystemThread.start(); 421 waitForAudioHandlerCreation(); 422 } 423 424 /** Waits for the volume handler to be created by the other thread. */ 425 private void waitForAudioHandlerCreation() { 426 synchronized(this) { 427 while (mAudioHandler == null) { 428 try { 429 // Wait for mAudioHandler to be set by the other thread 430 wait(); 431 } catch (InterruptedException e) { 432 Log.e(TAG, "Interrupted while waiting on volume handler."); 433 } 434 } 435 } 436 } 437 438 private void createStreamStates() { 439 int numStreamTypes = AudioSystem.getNumStreamTypes(); 440 VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes]; 441 442 for (int i = 0; i < numStreamTypes; i++) { 443 streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i); 444 } 445 446 // Correct stream index values for streams with aliases 447 for (int i = 0; i < numStreamTypes; i++) { 448 int device = getDeviceForStream(i); 449 if (STREAM_VOLUME_ALIAS[i] != i) { 450 int index = rescaleIndex(streams[i].getIndex(device, false /* lastAudible */), 451 STREAM_VOLUME_ALIAS[i], 452 i); 453 streams[i].mIndex.put(device, streams[i].getValidIndex(index)); 454 streams[i].applyDeviceVolume(device); 455 index = rescaleIndex(streams[i].getIndex(device, true /* lastAudible */), 456 STREAM_VOLUME_ALIAS[i], 457 i); 458 streams[i].mLastAudibleIndex.put(device, streams[i].getValidIndex(index)); 459 } 460 } 461 } 462 463 private void readPersistedSettings() { 464 final ContentResolver cr = mContentResolver; 465 466 int ringerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL); 467 // sanity check in case the settings are restored from a device with incompatible 468 // ringer modes 469 if (!AudioManager.isValidRingerMode(ringerMode)) { 470 ringerMode = AudioManager.RINGER_MODE_NORMAL; 471 System.putInt(cr, System.MODE_RINGER, ringerMode); 472 } 473 synchronized(mSettingsLock) { 474 mRingerMode = ringerMode; 475 } 476 477 mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0); 478 479 // make sure settings for ringer mode are consistent with device type: non voice capable 480 // devices (tablets) include media stream in silent mode whereas phones don't. 481 mRingerModeAffectedStreams = Settings.System.getInt(cr, 482 Settings.System.MODE_RINGER_STREAMS_AFFECTED, 483 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)| 484 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED))); 485 if (mVoiceCapable) { 486 mRingerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC); 487 } else { 488 mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC); 489 } 490 Settings.System.putInt(cr, 491 Settings.System.MODE_RINGER_STREAMS_AFFECTED, mRingerModeAffectedStreams); 492 493 mMuteAffectedStreams = System.getInt(cr, 494 System.MUTE_STREAMS_AFFECTED, 495 ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM))); 496 497 // Each stream will read its own persisted settings 498 499 // Broadcast the sticky intent 500 broadcastRingerMode(ringerMode); 501 502 // Broadcast vibrate settings 503 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); 504 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION); 505 506 // Restore the default media button receiver from the system settings 507 restoreMediaButtonReceiver(); 508 } 509 510 private int rescaleIndex(int index, int srcStream, int dstStream) { 511 return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex(); 512 } 513 514 /////////////////////////////////////////////////////////////////////////// 515 // IPC methods 516 /////////////////////////////////////////////////////////////////////////// 517 518 /** @see AudioManager#adjustVolume(int, int) */ 519 public void adjustVolume(int direction, int flags) { 520 adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags); 521 } 522 523 /** @see AudioManager#adjustVolume(int, int, int) */ 524 public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) { 525 526 int streamType; 527 if ((flags & AudioManager.FLAG_FORCE_STREAM) != 0) { 528 streamType = suggestedStreamType; 529 } else { 530 streamType = getActiveStreamType(suggestedStreamType); 531 } 532 533 // Play sounds on STREAM_RING only and if lock screen is not on. 534 if ((flags & AudioManager.FLAG_PLAY_SOUND) != 0 && 535 ((STREAM_VOLUME_ALIAS[streamType] != AudioSystem.STREAM_RING) 536 || (mKeyguardManager != null && mKeyguardManager.isKeyguardLocked()))) { 537 flags &= ~AudioManager.FLAG_PLAY_SOUND; 538 } 539 540 adjustStreamVolume(streamType, direction, flags); 541 } 542 543 /** @see AudioManager#adjustStreamVolume(int, int, int) */ 544 public void adjustStreamVolume(int streamType, int direction, int flags) { 545 ensureValidDirection(direction); 546 ensureValidStreamType(streamType); 547 548 // use stream type alias here so that streams with same alias have the same behavior, 549 // including with regard to silent mode control (e.g the use of STREAM_RING below and in 550 // checkForRingerModeChange() in place of STREAM_RING or STREAM_NOTIFICATION) 551 int streamTypeAlias = STREAM_VOLUME_ALIAS[streamType]; 552 VolumeStreamState streamState = mStreamStates[streamTypeAlias]; 553 554 final int device = getDeviceForStream(streamTypeAlias); 555 // get last audible index if stream is muted, current index otherwise 556 final int oldIndex = streamState.getIndex(device, 557 (streamState.muteCount() != 0) /* lastAudible */); 558 boolean adjustVolume = true; 559 560 // If either the client forces allowing ringer modes for this adjustment, 561 // or the stream type is one that is affected by ringer modes 562 if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) || 563 streamTypeAlias == AudioSystem.STREAM_RING || 564 (!mVoiceCapable && streamTypeAlias == AudioSystem.STREAM_MUSIC)) { 565 int ringerMode = getRingerMode(); 566 // do not vibrate if already in vibrate mode 567 if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) { 568 flags &= ~AudioManager.FLAG_VIBRATE; 569 } 570 // Check if the ringer mode changes with this volume adjustment. If 571 // it does, it will handle adjusting the volume, so we won't below 572 adjustVolume = checkForRingerModeChange(oldIndex, direction, streamTypeAlias); 573 } 574 575 // If stream is muted, adjust last audible index only 576 int index; 577 if (streamState.muteCount() != 0) { 578 if (adjustVolume) { 579 // adjust volume on all stream types sharing the same alias otherwise a query 580 // on last audible index for an alias would not give the correct value 581 int numStreamTypes = AudioSystem.getNumStreamTypes(); 582 for (int i = numStreamTypes - 1; i >= 0; i--) { 583 if (STREAM_VOLUME_ALIAS[i] == streamTypeAlias) { 584 VolumeStreamState s = mStreamStates[i]; 585 586 s.adjustLastAudibleIndex(direction, device); 587 // Post a persist volume msg 588 sendMsg(mAudioHandler, 589 MSG_PERSIST_VOLUME, 590 SENDMSG_REPLACE, 591 PERSIST_LAST_AUDIBLE, 592 device, 593 s, 594 PERSIST_DELAY); 595 } 596 } 597 } 598 index = streamState.getIndex(device, true /* lastAudible */); 599 } else { 600 if (adjustVolume && streamState.adjustIndex(direction, device)) { 601 // Post message to set system volume (it in turn will post a message 602 // to persist). Do not change volume if stream is muted. 603 sendMsg(mAudioHandler, 604 MSG_SET_DEVICE_VOLUME, 605 SENDMSG_NOOP, 606 device, 607 0, 608 streamState, 609 0); 610 } 611 index = streamState.getIndex(device, false /* lastAudible */); 612 } 613 614 sendVolumeUpdate(streamType, oldIndex, index, flags); 615 } 616 617 /** @see AudioManager#adjustMasterVolume(int) */ 618 public void adjustMasterVolume(int direction) { 619 ensureValidDirection(direction); 620 621 float volume = AudioSystem.getMasterVolume(); 622 if (volume >= 0.0) { 623 if (direction == AudioManager.ADJUST_RAISE) { 624 volume += MASTER_VOLUME_INCREMENT; 625 if (volume > 1.0f) volume = 1.0f; 626 } else if (direction == AudioManager.ADJUST_LOWER) { 627 volume -= MASTER_VOLUME_INCREMENT; 628 if (volume < 0.0f) volume = 0.0f; 629 } 630 AudioSystem.setMasterVolume(volume); 631 long origCallerIdentityToken = Binder.clearCallingIdentity(); 632 Settings.System.putFloat(mContentResolver, Settings.System.VOLUME_MASTER, volume); 633 Binder.restoreCallingIdentity(origCallerIdentityToken); 634 } 635 } 636 637 /** @see AudioManager#setStreamVolume(int, int, int) */ 638 public void setStreamVolume(int streamType, int index, int flags) { 639 ensureValidStreamType(streamType); 640 VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]]; 641 642 final int device = getDeviceForStream(streamType); 643 // get last audible index if stream is muted, current index otherwise 644 final int oldIndex = streamState.getIndex(device, 645 (streamState.muteCount() != 0) /* lastAudible */); 646 647 // setting ring or notifications volume to 0 on voice capable devices enters silent mode 648 if (mVoiceCapable && (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) || 649 (STREAM_VOLUME_ALIAS[streamType] == AudioSystem.STREAM_RING))) { 650 int newRingerMode; 651 if (index == 0) { 652 newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1 653 ? AudioManager.RINGER_MODE_VIBRATE 654 : AudioManager.RINGER_MODE_SILENT; 655 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], 656 index, 657 device, 658 false, 659 true); 660 } else { 661 newRingerMode = AudioManager.RINGER_MODE_NORMAL; 662 } 663 setRingerMode(newRingerMode); 664 } 665 666 index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]); 667 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, device, false, true); 668 // get last audible index if stream is muted, current index otherwise 669 index = streamState.getIndex(device, 670 (streamState.muteCount() != 0) /* lastAudible */); 671 672 sendVolumeUpdate(streamType, oldIndex, index, flags); 673 } 674 675 // UI update and Broadcast Intent 676 private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) { 677 if (!mVoiceCapable && (streamType == AudioSystem.STREAM_RING)) { 678 streamType = AudioSystem.STREAM_NOTIFICATION; 679 } 680 681 mVolumePanel.postVolumeChanged(streamType, flags); 682 683 oldIndex = (oldIndex + 5) / 10; 684 index = (index + 5) / 10; 685 Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION); 686 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType); 687 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index); 688 intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex); 689 mContext.sendBroadcast(intent); 690 } 691 692 /** 693 * Sets the stream state's index, and posts a message to set system volume. 694 * This will not call out to the UI. Assumes a valid stream type. 695 * 696 * @param streamType Type of the stream 697 * @param index Desired volume index of the stream 698 * @param device the device whose volume must be changed 699 * @param force If true, set the volume even if the desired volume is same 700 * as the current volume. 701 * @param lastAudible If true, stores new index as last audible one 702 */ 703 private void setStreamVolumeInt(int streamType, 704 int index, 705 int device, 706 boolean force, 707 boolean lastAudible) { 708 VolumeStreamState streamState = mStreamStates[streamType]; 709 710 // If stream is muted, set last audible index only 711 if (streamState.muteCount() != 0) { 712 // Do not allow last audible index to be 0 713 if (index != 0) { 714 streamState.setLastAudibleIndex(index, device); 715 // Post a persist volume msg 716 sendMsg(mAudioHandler, 717 MSG_PERSIST_VOLUME, 718 SENDMSG_REPLACE, 719 PERSIST_LAST_AUDIBLE, 720 device, 721 streamState, 722 PERSIST_DELAY); 723 } 724 } else { 725 if (streamState.setIndex(index, device, lastAudible) || force) { 726 // Post message to set system volume (it in turn will post a message 727 // to persist). 728 sendMsg(mAudioHandler, 729 MSG_SET_DEVICE_VOLUME, 730 SENDMSG_NOOP, 731 device, 732 0, 733 streamState, 734 0); 735 } 736 } 737 } 738 739 /** @see AudioManager#setStreamSolo(int, boolean) */ 740 public void setStreamSolo(int streamType, boolean state, IBinder cb) { 741 for (int stream = 0; stream < mStreamStates.length; stream++) { 742 if (!isStreamAffectedByMute(stream) || stream == streamType) continue; 743 // Bring back last audible volume 744 mStreamStates[stream].mute(cb, state); 745 } 746 } 747 748 /** @see AudioManager#setStreamMute(int, boolean) */ 749 public void setStreamMute(int streamType, boolean state, IBinder cb) { 750 if (isStreamAffectedByMute(streamType)) { 751 mStreamStates[streamType].mute(cb, state); 752 } 753 } 754 755 /** get stream mute state. */ 756 public boolean isStreamMute(int streamType) { 757 return (mStreamStates[streamType].muteCount() != 0); 758 } 759 760 /** @see AudioManager#getStreamVolume(int) */ 761 public int getStreamVolume(int streamType) { 762 ensureValidStreamType(streamType); 763 int device = getDeviceForStream(streamType); 764 return (mStreamStates[streamType].getIndex(device, false /* lastAudible */) + 5) / 10; 765 } 766 767 /** @see AudioManager#getStreamMaxVolume(int) */ 768 public int getStreamMaxVolume(int streamType) { 769 ensureValidStreamType(streamType); 770 return (mStreamStates[streamType].getMaxIndex() + 5) / 10; 771 } 772 773 774 /** Get last audible volume before stream was muted. */ 775 public int getLastAudibleStreamVolume(int streamType) { 776 ensureValidStreamType(streamType); 777 int device = getDeviceForStream(streamType); 778 return (mStreamStates[streamType].getIndex(device, true /* lastAudible */) + 5) / 10; 779 } 780 781 /** @see AudioManager#getRingerMode() */ 782 public int getRingerMode() { 783 synchronized(mSettingsLock) { 784 return mRingerMode; 785 } 786 } 787 788 private void ensureValidRingerMode(int ringerMode) { 789 if (!AudioManager.isValidRingerMode(ringerMode)) { 790 throw new IllegalArgumentException("Bad ringer mode " + ringerMode); 791 } 792 } 793 794 /** @see AudioManager#setRingerMode(int) */ 795 public void setRingerMode(int ringerMode) { 796 ensureValidRingerMode(ringerMode); 797 if (ringerMode != getRingerMode()) { 798 setRingerModeInt(ringerMode, true); 799 // Send sticky broadcast 800 broadcastRingerMode(ringerMode); 801 } 802 } 803 804 private void setRingerModeInt(int ringerMode, boolean persist) { 805 synchronized(mSettingsLock) { 806 mRingerMode = ringerMode; 807 } 808 809 // Mute stream if not previously muted by ringer mode and ringer mode 810 // is not RINGER_MODE_NORMAL and stream is affected by ringer mode. 811 // Unmute stream if previously muted by ringer mode and ringer mode 812 // is RINGER_MODE_NORMAL or stream is not affected by ringer mode. 813 int numStreamTypes = AudioSystem.getNumStreamTypes(); 814 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 815 if (isStreamMutedByRingerMode(streamType)) { 816 if (!isStreamAffectedByRingerMode(streamType) || 817 ringerMode == AudioManager.RINGER_MODE_NORMAL) { 818 // ring and notifications volume should never be 0 when not silenced 819 // on voice capable devices 820 if (mVoiceCapable && 821 STREAM_VOLUME_ALIAS[streamType] == AudioSystem.STREAM_RING) { 822 823 Set set = mStreamStates[streamType].mLastAudibleIndex.entrySet(); 824 Iterator i = set.iterator(); 825 while (i.hasNext()) { 826 Map.Entry entry = (Map.Entry)i.next(); 827 if ((Integer)entry.getValue() == 0) { 828 entry.setValue(10); 829 } 830 } 831 } 832 mStreamStates[streamType].mute(null, false); 833 mRingerModeMutedStreams &= ~(1 << streamType); 834 } 835 } else { 836 if (isStreamAffectedByRingerMode(streamType) && 837 ringerMode != AudioManager.RINGER_MODE_NORMAL) { 838 mStreamStates[streamType].mute(null, true); 839 mRingerModeMutedStreams |= (1 << streamType); 840 } 841 } 842 } 843 844 // Post a persist ringer mode msg 845 if (persist) { 846 sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, 847 SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY); 848 } 849 } 850 851 /** @see AudioManager#shouldVibrate(int) */ 852 public boolean shouldVibrate(int vibrateType) { 853 854 switch (getVibrateSetting(vibrateType)) { 855 856 case AudioManager.VIBRATE_SETTING_ON: 857 return getRingerMode() != AudioManager.RINGER_MODE_SILENT; 858 859 case AudioManager.VIBRATE_SETTING_ONLY_SILENT: 860 return getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; 861 862 case AudioManager.VIBRATE_SETTING_OFF: 863 // return false, even for incoming calls 864 return false; 865 866 default: 867 return false; 868 } 869 } 870 871 /** @see AudioManager#getVibrateSetting(int) */ 872 public int getVibrateSetting(int vibrateType) { 873 return (mVibrateSetting >> (vibrateType * 2)) & 3; 874 } 875 876 /** @see AudioManager#setVibrateSetting(int, int) */ 877 public void setVibrateSetting(int vibrateType, int vibrateSetting) { 878 879 mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting); 880 881 // Broadcast change 882 broadcastVibrateSetting(vibrateType); 883 884 // Post message to set ringer mode (it in turn will post a message 885 // to persist) 886 sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SENDMSG_NOOP, 0, 0, 887 null, 0); 888 } 889 890 /** 891 * @see #setVibrateSetting(int, int) 892 */ 893 public static int getValueForVibrateSetting(int existingValue, int vibrateType, 894 int vibrateSetting) { 895 896 // First clear the existing setting. Each vibrate type has two bits in 897 // the value. Note '3' is '11' in binary. 898 existingValue &= ~(3 << (vibrateType * 2)); 899 900 // Set into the old value 901 existingValue |= (vibrateSetting & 3) << (vibrateType * 2); 902 903 return existingValue; 904 } 905 906 private class SetModeDeathHandler implements IBinder.DeathRecipient { 907 private IBinder mCb; // To be notified of client's death 908 private int mPid; 909 private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client 910 911 SetModeDeathHandler(IBinder cb, int pid) { 912 mCb = cb; 913 mPid = pid; 914 } 915 916 public void binderDied() { 917 int newModeOwnerPid = 0; 918 synchronized(mSetModeDeathHandlers) { 919 Log.w(TAG, "setMode() client died"); 920 int index = mSetModeDeathHandlers.indexOf(this); 921 if (index < 0) { 922 Log.w(TAG, "unregistered setMode() client died"); 923 } else { 924 newModeOwnerPid = setModeInt(AudioSystem.MODE_NORMAL, mCb, mPid); 925 } 926 } 927 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all 928 // SCO connections not started by the application changing the mode 929 if (newModeOwnerPid != 0) { 930 disconnectBluetoothSco(newModeOwnerPid); 931 } 932 } 933 934 public int getPid() { 935 return mPid; 936 } 937 938 public void setMode(int mode) { 939 mMode = mode; 940 } 941 942 public int getMode() { 943 return mMode; 944 } 945 946 public IBinder getBinder() { 947 return mCb; 948 } 949 } 950 951 /** @see AudioManager#setMode(int) */ 952 public void setMode(int mode, IBinder cb) { 953 if (!checkAudioSettingsPermission("setMode()")) { 954 return; 955 } 956 957 if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) { 958 return; 959 } 960 961 int newModeOwnerPid = 0; 962 synchronized(mSetModeDeathHandlers) { 963 if (mode == AudioSystem.MODE_CURRENT) { 964 mode = mMode; 965 } 966 newModeOwnerPid = setModeInt(mode, cb, Binder.getCallingPid()); 967 } 968 // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all 969 // SCO connections not started by the application changing the mode 970 if (newModeOwnerPid != 0) { 971 disconnectBluetoothSco(newModeOwnerPid); 972 } 973 } 974 975 // must be called synchronized on mSetModeDeathHandlers 976 // setModeInt() returns a valid PID if the audio mode was successfully set to 977 // any mode other than NORMAL. 978 int setModeInt(int mode, IBinder cb, int pid) { 979 int newModeOwnerPid = 0; 980 if (cb == null) { 981 Log.e(TAG, "setModeInt() called with null binder"); 982 return newModeOwnerPid; 983 } 984 985 SetModeDeathHandler hdlr = null; 986 Iterator iter = mSetModeDeathHandlers.iterator(); 987 while (iter.hasNext()) { 988 SetModeDeathHandler h = (SetModeDeathHandler)iter.next(); 989 if (h.getPid() == pid) { 990 hdlr = h; 991 // Remove from client list so that it is re-inserted at top of list 992 iter.remove(); 993 hdlr.getBinder().unlinkToDeath(hdlr, 0); 994 break; 995 } 996 } 997 int status = AudioSystem.AUDIO_STATUS_OK; 998 do { 999 if (mode == AudioSystem.MODE_NORMAL) { 1000 // get new mode from client at top the list if any 1001 if (!mSetModeDeathHandlers.isEmpty()) { 1002 hdlr = mSetModeDeathHandlers.get(0); 1003 cb = hdlr.getBinder(); 1004 mode = hdlr.getMode(); 1005 } 1006 } else { 1007 if (hdlr == null) { 1008 hdlr = new SetModeDeathHandler(cb, pid); 1009 } 1010 // Register for client death notification 1011 try { 1012 cb.linkToDeath(hdlr, 0); 1013 } catch (RemoteException e) { 1014 // Client has died! 1015 Log.w(TAG, "setMode() could not link to "+cb+" binder death"); 1016 } 1017 1018 // Last client to call setMode() is always at top of client list 1019 // as required by SetModeDeathHandler.binderDied() 1020 mSetModeDeathHandlers.add(0, hdlr); 1021 hdlr.setMode(mode); 1022 } 1023 1024 if (mode != mMode) { 1025 status = AudioSystem.setPhoneState(mode); 1026 if (status == AudioSystem.AUDIO_STATUS_OK) { 1027 mMode = mode; 1028 } else { 1029 if (hdlr != null) { 1030 mSetModeDeathHandlers.remove(hdlr); 1031 cb.unlinkToDeath(hdlr, 0); 1032 } 1033 // force reading new top of mSetModeDeathHandlers stack 1034 mode = AudioSystem.MODE_NORMAL; 1035 } 1036 } else { 1037 status = AudioSystem.AUDIO_STATUS_OK; 1038 } 1039 } while (status != AudioSystem.AUDIO_STATUS_OK && !mSetModeDeathHandlers.isEmpty()); 1040 1041 if (status == AudioSystem.AUDIO_STATUS_OK) { 1042 if (mode != AudioSystem.MODE_NORMAL) { 1043 if (mSetModeDeathHandlers.isEmpty()) { 1044 Log.e(TAG, "setMode() different from MODE_NORMAL with empty mode client stack"); 1045 } else { 1046 newModeOwnerPid = mSetModeDeathHandlers.get(0).getPid(); 1047 } 1048 } 1049 int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); 1050 int device = getDeviceForStream(streamType); 1051 int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].getIndex(device, false); 1052 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, device, true, false); 1053 } 1054 return newModeOwnerPid; 1055 } 1056 1057 /** @see AudioManager#getMode() */ 1058 public int getMode() { 1059 return mMode; 1060 } 1061 1062 /** @see AudioManager#playSoundEffect(int) */ 1063 public void playSoundEffect(int effectType) { 1064 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_NOOP, 1065 effectType, -1, null, 0); 1066 } 1067 1068 /** @see AudioManager#playSoundEffect(int, float) */ 1069 public void playSoundEffectVolume(int effectType, float volume) { 1070 loadSoundEffects(); 1071 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_NOOP, 1072 effectType, (int) (volume * 1000), null, 0); 1073 } 1074 1075 /** 1076 * Loads samples into the soundpool. 1077 * This method must be called at first when sound effects are enabled 1078 */ 1079 public boolean loadSoundEffects() { 1080 int status; 1081 1082 synchronized (mSoundEffectsLock) { 1083 if (!mBootCompleted) { 1084 Log.w(TAG, "loadSoundEffects() called before boot complete"); 1085 return false; 1086 } 1087 1088 if (mSoundPool != null) { 1089 return true; 1090 } 1091 mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0); 1092 1093 try { 1094 mSoundPoolCallBack = null; 1095 mSoundPoolListenerThread = new SoundPoolListenerThread(); 1096 mSoundPoolListenerThread.start(); 1097 // Wait for mSoundPoolCallBack to be set by the other thread 1098 mSoundEffectsLock.wait(); 1099 } catch (InterruptedException e) { 1100 Log.w(TAG, "Interrupted while waiting sound pool listener thread."); 1101 } 1102 1103 if (mSoundPoolCallBack == null) { 1104 Log.w(TAG, "loadSoundEffects() could not create SoundPool listener or thread"); 1105 if (mSoundPoolLooper != null) { 1106 mSoundPoolLooper.quit(); 1107 mSoundPoolLooper = null; 1108 } 1109 mSoundPoolListenerThread = null; 1110 mSoundPool.release(); 1111 mSoundPool = null; 1112 return false; 1113 } 1114 /* 1115 * poolId table: The value -1 in this table indicates that corresponding 1116 * file (same index in SOUND_EFFECT_FILES[] has not been loaded. 1117 * Once loaded, the value in poolId is the sample ID and the same 1118 * sample can be reused for another effect using the same file. 1119 */ 1120 int[] poolId = new int[SOUND_EFFECT_FILES.length]; 1121 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { 1122 poolId[fileIdx] = -1; 1123 } 1124 /* 1125 * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded. 1126 * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0: 1127 * this indicates we have a valid sample loaded for this effect. 1128 */ 1129 1130 int lastSample = 0; 1131 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { 1132 // Do not load sample if this effect uses the MediaPlayer 1133 if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) { 1134 continue; 1135 } 1136 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) { 1137 String filePath = Environment.getRootDirectory() 1138 + SOUND_EFFECTS_PATH 1139 + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]]; 1140 int sampleId = mSoundPool.load(filePath, 0); 1141 if (sampleId <= 0) { 1142 Log.w(TAG, "Soundpool could not load file: "+filePath); 1143 } else { 1144 SOUND_EFFECT_FILES_MAP[effect][1] = sampleId; 1145 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId; 1146 lastSample = sampleId; 1147 } 1148 } else { 1149 SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]]; 1150 } 1151 } 1152 // wait for all samples to be loaded 1153 if (lastSample != 0) { 1154 mSoundPoolCallBack.setLastSample(lastSample); 1155 1156 try { 1157 mSoundEffectsLock.wait(); 1158 status = mSoundPoolCallBack.status(); 1159 } catch (java.lang.InterruptedException e) { 1160 Log.w(TAG, "Interrupted while waiting sound pool callback."); 1161 status = -1; 1162 } 1163 } else { 1164 status = -1; 1165 } 1166 1167 if (mSoundPoolLooper != null) { 1168 mSoundPoolLooper.quit(); 1169 mSoundPoolLooper = null; 1170 } 1171 mSoundPoolListenerThread = null; 1172 if (status != 0) { 1173 Log.w(TAG, 1174 "loadSoundEffects(), Error " 1175 + ((lastSample != 0) ? mSoundPoolCallBack.status() : -1) 1176 + " while loading samples"); 1177 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { 1178 if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) { 1179 SOUND_EFFECT_FILES_MAP[effect][1] = -1; 1180 } 1181 } 1182 1183 mSoundPool.release(); 1184 mSoundPool = null; 1185 } 1186 } 1187 return (status == 0); 1188 } 1189 1190 /** 1191 * Unloads samples from the sound pool. 1192 * This method can be called to free some memory when 1193 * sound effects are disabled. 1194 */ 1195 public void unloadSoundEffects() { 1196 synchronized (mSoundEffectsLock) { 1197 if (mSoundPool == null) { 1198 return; 1199 } 1200 1201 mAudioHandler.removeMessages(MSG_LOAD_SOUND_EFFECTS); 1202 mAudioHandler.removeMessages(MSG_PLAY_SOUND_EFFECT); 1203 1204 int[] poolId = new int[SOUND_EFFECT_FILES.length]; 1205 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { 1206 poolId[fileIdx] = 0; 1207 } 1208 1209 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { 1210 if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) { 1211 continue; 1212 } 1213 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) { 1214 mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]); 1215 SOUND_EFFECT_FILES_MAP[effect][1] = -1; 1216 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1; 1217 } 1218 } 1219 mSoundPool.release(); 1220 mSoundPool = null; 1221 } 1222 } 1223 1224 class SoundPoolListenerThread extends Thread { 1225 public SoundPoolListenerThread() { 1226 super("SoundPoolListenerThread"); 1227 } 1228 1229 @Override 1230 public void run() { 1231 1232 Looper.prepare(); 1233 mSoundPoolLooper = Looper.myLooper(); 1234 1235 synchronized (mSoundEffectsLock) { 1236 if (mSoundPool != null) { 1237 mSoundPoolCallBack = new SoundPoolCallback(); 1238 mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack); 1239 } 1240 mSoundEffectsLock.notify(); 1241 } 1242 Looper.loop(); 1243 } 1244 } 1245 1246 private final class SoundPoolCallback implements 1247 android.media.SoundPool.OnLoadCompleteListener { 1248 1249 int mStatus; 1250 int mLastSample; 1251 1252 public int status() { 1253 return mStatus; 1254 } 1255 1256 public void setLastSample(int sample) { 1257 mLastSample = sample; 1258 } 1259 1260 public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { 1261 synchronized (mSoundEffectsLock) { 1262 if (status != 0) { 1263 mStatus = status; 1264 } 1265 if (sampleId == mLastSample) { 1266 mSoundEffectsLock.notify(); 1267 } 1268 } 1269 } 1270 } 1271 1272 /** @see AudioManager#reloadAudioSettings() */ 1273 public void reloadAudioSettings() { 1274 // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings 1275 readPersistedSettings(); 1276 1277 // restore volume settings 1278 int numStreamTypes = AudioSystem.getNumStreamTypes(); 1279 for (int streamType = 0; streamType < numStreamTypes; streamType++) { 1280 VolumeStreamState streamState = mStreamStates[streamType]; 1281 1282 streamState.readSettings(); 1283 1284 // unmute stream that was muted but is not affect by mute anymore 1285 if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) { 1286 int size = streamState.mDeathHandlers.size(); 1287 for (int i = 0; i < size; i++) { 1288 streamState.mDeathHandlers.get(i).mMuteCount = 1; 1289 streamState.mDeathHandlers.get(i).mute(false); 1290 } 1291 } 1292 // apply stream volume 1293 if (streamState.muteCount() == 0) { 1294 streamState.applyAllVolumes(); 1295 } 1296 } 1297 1298 // apply new ringer mode 1299 setRingerModeInt(getRingerMode(), false); 1300 } 1301 1302 /** @see AudioManager#setSpeakerphoneOn() */ 1303 public void setSpeakerphoneOn(boolean on){ 1304 if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) { 1305 return; 1306 } 1307 mForcedUseForComm = on ? AudioSystem.FORCE_SPEAKER : AudioSystem.FORCE_NONE; 1308 1309 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE, 1310 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0); 1311 } 1312 1313 /** @see AudioManager#isSpeakerphoneOn() */ 1314 public boolean isSpeakerphoneOn() { 1315 return (mForcedUseForComm == AudioSystem.FORCE_SPEAKER); 1316 } 1317 1318 /** @see AudioManager#setBluetoothScoOn() */ 1319 public void setBluetoothScoOn(boolean on){ 1320 if (!checkAudioSettingsPermission("setBluetoothScoOn()")) { 1321 return; 1322 } 1323 mForcedUseForComm = on ? AudioSystem.FORCE_BT_SCO : AudioSystem.FORCE_NONE; 1324 1325 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE, 1326 AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0); 1327 sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE, 1328 AudioSystem.FOR_RECORD, mForcedUseForComm, null, 0); 1329 } 1330 1331 /** @see AudioManager#isBluetoothScoOn() */ 1332 public boolean isBluetoothScoOn() { 1333 return (mForcedUseForComm == AudioSystem.FORCE_BT_SCO); 1334 } 1335 1336 /** @see AudioManager#startBluetoothSco() */ 1337 public void startBluetoothSco(IBinder cb){ 1338 if (!checkAudioSettingsPermission("startBluetoothSco()") || 1339 !mBootCompleted) { 1340 return; 1341 } 1342 ScoClient client = getScoClient(cb, true); 1343 client.incCount(); 1344 } 1345 1346 /** @see AudioManager#stopBluetoothSco() */ 1347 public void stopBluetoothSco(IBinder cb){ 1348 if (!checkAudioSettingsPermission("stopBluetoothSco()") || 1349 !mBootCompleted) { 1350 return; 1351 } 1352 ScoClient client = getScoClient(cb, false); 1353 if (client != null) { 1354 client.decCount(); 1355 } 1356 } 1357 1358 private class ScoClient implements IBinder.DeathRecipient { 1359 private IBinder mCb; // To be notified of client's death 1360 private int mCreatorPid; 1361 private int mStartcount; // number of SCO connections started by this client 1362 1363 ScoClient(IBinder cb) { 1364 mCb = cb; 1365 mCreatorPid = Binder.getCallingPid(); 1366 mStartcount = 0; 1367 } 1368 1369 public void binderDied() { 1370 synchronized(mScoClients) { 1371 Log.w(TAG, "SCO client died"); 1372 int index = mScoClients.indexOf(this); 1373 if (index < 0) { 1374 Log.w(TAG, "unregistered SCO client died"); 1375 } else { 1376 clearCount(true); 1377 mScoClients.remove(this); 1378 } 1379 } 1380 } 1381 1382 public void incCount() { 1383 synchronized(mScoClients) { 1384 requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED); 1385 if (mStartcount == 0) { 1386 try { 1387 mCb.linkToDeath(this, 0); 1388 } catch (RemoteException e) { 1389 // client has already died! 1390 Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death"); 1391 } 1392 } 1393 mStartcount++; 1394 } 1395 } 1396 1397 public void decCount() { 1398 synchronized(mScoClients) { 1399 if (mStartcount == 0) { 1400 Log.w(TAG, "ScoClient.decCount() already 0"); 1401 } else { 1402 mStartcount--; 1403 if (mStartcount == 0) { 1404 try { 1405 mCb.unlinkToDeath(this, 0); 1406 } catch (NoSuchElementException e) { 1407 Log.w(TAG, "decCount() going to 0 but not registered to binder"); 1408 } 1409 } 1410 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED); 1411 } 1412 } 1413 } 1414 1415 public void clearCount(boolean stopSco) { 1416 synchronized(mScoClients) { 1417 if (mStartcount != 0) { 1418 try { 1419 mCb.unlinkToDeath(this, 0); 1420 } catch (NoSuchElementException e) { 1421 Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder"); 1422 } 1423 } 1424 mStartcount = 0; 1425 if (stopSco) { 1426 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED); 1427 } 1428 } 1429 } 1430 1431 public int getCount() { 1432 return mStartcount; 1433 } 1434 1435 public IBinder getBinder() { 1436 return mCb; 1437 } 1438 1439 public int getPid() { 1440 return mCreatorPid; 1441 } 1442 1443 public int totalCount() { 1444 synchronized(mScoClients) { 1445 int count = 0; 1446 int size = mScoClients.size(); 1447 for (int i = 0; i < size; i++) { 1448 count += mScoClients.get(i).getCount(); 1449 } 1450 return count; 1451 } 1452 } 1453 1454 private void requestScoState(int state) { 1455 checkScoAudioState(); 1456 if (totalCount() == 0) { 1457 if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) { 1458 // Make sure that the state transitions to CONNECTING even if we cannot initiate 1459 // the connection. 1460 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING); 1461 // Accept SCO audio activation only in NORMAL audio mode or if the mode is 1462 // currently controlled by the same client process. 1463 synchronized(mSetModeDeathHandlers) { 1464 if ((mSetModeDeathHandlers.isEmpty() || 1465 mSetModeDeathHandlers.get(0).getPid() == mCreatorPid) && 1466 (mScoAudioState == SCO_STATE_INACTIVE || 1467 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) { 1468 if (mScoAudioState == SCO_STATE_INACTIVE) { 1469 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) { 1470 if (mBluetoothHeadset.startScoUsingVirtualVoiceCall( 1471 mBluetoothHeadsetDevice)) { 1472 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL; 1473 } else { 1474 broadcastScoConnectionState( 1475 AudioManager.SCO_AUDIO_STATE_DISCONNECTED); 1476 } 1477 } else if (getBluetoothHeadset()) { 1478 mScoAudioState = SCO_STATE_ACTIVATE_REQ; 1479 } 1480 } else { 1481 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL; 1482 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED); 1483 } 1484 } else { 1485 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED); 1486 } 1487 } 1488 } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED && 1489 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL || 1490 mScoAudioState == SCO_STATE_ACTIVATE_REQ)) { 1491 if (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) { 1492 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) { 1493 if (!mBluetoothHeadset.stopScoUsingVirtualVoiceCall( 1494 mBluetoothHeadsetDevice)) { 1495 mScoAudioState = SCO_STATE_INACTIVE; 1496 broadcastScoConnectionState( 1497 AudioManager.SCO_AUDIO_STATE_DISCONNECTED); 1498 } 1499 } else if (getBluetoothHeadset()) { 1500 mScoAudioState = SCO_STATE_DEACTIVATE_REQ; 1501 } 1502 } else { 1503 mScoAudioState = SCO_STATE_INACTIVE; 1504 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED); 1505 } 1506 } 1507 } 1508 } 1509 } 1510 1511 private void checkScoAudioState() { 1512 if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null && 1513 mScoAudioState == SCO_STATE_INACTIVE && 1514 mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice) 1515 != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) { 1516 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL; 1517 } 1518 } 1519 1520 private ScoClient getScoClient(IBinder cb, boolean create) { 1521 synchronized(mScoClients) { 1522 ScoClient client = null; 1523 int size = mScoClients.size(); 1524 for (int i = 0; i < size; i++) { 1525 client = mScoClients.get(i); 1526 if (client.getBinder() == cb) 1527 return client; 1528 } 1529 if (create) { 1530 client = new ScoClient(cb); 1531 mScoClients.add(client); 1532 } 1533 return client; 1534 } 1535 } 1536 1537 public void clearAllScoClients(int exceptPid, boolean stopSco) { 1538 synchronized(mScoClients) { 1539 ScoClient savedClient = null; 1540 int size = mScoClients.size(); 1541 for (int i = 0; i < size; i++) { 1542 ScoClient cl = mScoClients.get(i); 1543 if (cl.getPid() != exceptPid) { 1544 cl.clearCount(stopSco); 1545 } else { 1546 savedClient = cl; 1547 } 1548 } 1549 mScoClients.clear(); 1550 if (savedClient != null) { 1551 mScoClients.add(savedClient); 1552 } 1553 } 1554 } 1555 1556 private boolean getBluetoothHeadset() { 1557 boolean result = false; 1558 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 1559 if (adapter != null) { 1560 result = adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener, 1561 BluetoothProfile.HEADSET); 1562 } 1563 // If we could not get a bluetooth headset proxy, send a failure message 1564 // without delay to reset the SCO audio state and clear SCO clients. 1565 // If we could get a proxy, send a delayed failure message that will reset our state 1566 // in case we don't receive onServiceConnected(). 1567 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, 1568 SENDMSG_REPLACE, 0, 0, null, result ? BT_HEADSET_CNCT_TIMEOUT_MS : 0); 1569 return result; 1570 } 1571 1572 private void disconnectBluetoothSco(int exceptPid) { 1573 synchronized(mScoClients) { 1574 checkScoAudioState(); 1575 if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL || 1576 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) { 1577 if (mBluetoothHeadsetDevice != null) { 1578 if (mBluetoothHeadset != null) { 1579 if (!mBluetoothHeadset.stopVoiceRecognition( 1580 mBluetoothHeadsetDevice)) { 1581 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, 1582 SENDMSG_REPLACE, 0, 0, null, 0); 1583 } 1584 } else if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL && 1585 getBluetoothHeadset()) { 1586 mScoAudioState = SCO_STATE_DEACTIVATE_EXT_REQ; 1587 } 1588 } 1589 } else { 1590 clearAllScoClients(exceptPid, true); 1591 } 1592 } 1593 } 1594 1595 private void resetBluetoothSco() { 1596 synchronized(mScoClients) { 1597 clearAllScoClients(0, false); 1598 mScoAudioState = SCO_STATE_INACTIVE; 1599 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED); 1600 } 1601 } 1602 1603 private void broadcastScoConnectionState(int state) { 1604 if (state != mScoConnectionState) { 1605 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); 1606 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state); 1607 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE, 1608 mScoConnectionState); 1609 mContext.sendStickyBroadcast(newIntent); 1610 mScoConnectionState = state; 1611 } 1612 } 1613 1614 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener = 1615 new BluetoothProfile.ServiceListener() { 1616 public void onServiceConnected(int profile, BluetoothProfile proxy) { 1617 BluetoothDevice btDevice; 1618 List<BluetoothDevice> deviceList; 1619 switch(profile) { 1620 case BluetoothProfile.A2DP: 1621 BluetoothA2dp a2dp = (BluetoothA2dp) proxy; 1622 deviceList = a2dp.getConnectedDevices(); 1623 if (deviceList.size() > 0) { 1624 btDevice = deviceList.get(0); 1625 handleA2dpConnectionStateChange(btDevice, a2dp.getConnectionState(btDevice)); 1626 } 1627 break; 1628 1629 case BluetoothProfile.HEADSET: 1630 synchronized (mScoClients) { 1631 // Discard timeout message 1632 mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED); 1633 mBluetoothHeadset = (BluetoothHeadset) proxy; 1634 deviceList = mBluetoothHeadset.getConnectedDevices(); 1635 if (deviceList.size() > 0) { 1636 mBluetoothHeadsetDevice = deviceList.get(0); 1637 } else { 1638 mBluetoothHeadsetDevice = null; 1639 } 1640 // Refresh SCO audio state 1641 checkScoAudioState(); 1642 // Continue pending action if any 1643 if (mScoAudioState == SCO_STATE_ACTIVATE_REQ || 1644 mScoAudioState == SCO_STATE_DEACTIVATE_REQ || 1645 mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) { 1646 boolean status = false; 1647 if (mBluetoothHeadsetDevice != null) { 1648 switch (mScoAudioState) { 1649 case SCO_STATE_ACTIVATE_REQ: 1650 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL; 1651 status = mBluetoothHeadset.startScoUsingVirtualVoiceCall( 1652 mBluetoothHeadsetDevice); 1653 break; 1654 case SCO_STATE_DEACTIVATE_REQ: 1655 status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall( 1656 mBluetoothHeadsetDevice); 1657 break; 1658 case SCO_STATE_DEACTIVATE_EXT_REQ: 1659 status = mBluetoothHeadset.stopVoiceRecognition( 1660 mBluetoothHeadsetDevice); 1661 } 1662 } 1663 if (!status) { 1664 sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, 1665 SENDMSG_REPLACE, 0, 0, null, 0); 1666 } 1667 } 1668 } 1669 break; 1670 1671 default: 1672 break; 1673 } 1674 } 1675 public void onServiceDisconnected(int profile) { 1676 switch(profile) { 1677 case BluetoothProfile.A2DP: 1678 synchronized (mConnectedDevices) { 1679 if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) { 1680 makeA2dpDeviceUnavailableNow( 1681 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)); 1682 } 1683 } 1684 break; 1685 1686 case BluetoothProfile.HEADSET: 1687 synchronized (mScoClients) { 1688 mBluetoothHeadset = null; 1689 } 1690 break; 1691 1692 default: 1693 break; 1694 } 1695 } 1696 }; 1697 1698 /////////////////////////////////////////////////////////////////////////// 1699 // Internal methods 1700 /////////////////////////////////////////////////////////////////////////// 1701 1702 /** 1703 * Checks if the adjustment should change ringer mode instead of just 1704 * adjusting volume. If so, this will set the proper ringer mode and volume 1705 * indices on the stream states. 1706 */ 1707 private boolean checkForRingerModeChange(int oldIndex, int direction, int streamType) { 1708 boolean adjustVolumeIndex = true; 1709 int ringerMode = getRingerMode(); 1710 int newRingerMode = ringerMode; 1711 int uiIndex = (oldIndex + 5) / 10; 1712 boolean vibeInSilent = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1; 1713 1714 if (ringerMode == RINGER_MODE_NORMAL) { 1715 if ((direction == AudioManager.ADJUST_LOWER) && (uiIndex <= 1)) { 1716 // enter silent mode if current index is the last audible one and not repeating a 1717 // volume key down 1718 if (vibeInSilent || mPrevVolDirection != AudioManager.ADJUST_LOWER) { 1719 // "silent mode", but which one? 1720 newRingerMode = vibeInSilent ? RINGER_MODE_VIBRATE : RINGER_MODE_SILENT; 1721 } 1722 if (uiIndex == 0 || 1723 (!vibeInSilent && 1724 mPrevVolDirection == AudioManager.ADJUST_LOWER && 1725 mVoiceCapable && streamType == AudioSystem.STREAM_RING)) { 1726 adjustVolumeIndex = false; 1727 } 1728 } 1729 } else if (ringerMode == RINGER_MODE_VIBRATE) { 1730 if ((direction == AudioManager.ADJUST_LOWER)) { 1731 // Set it to silent, if it wasn't a long-press 1732 if (mPrevVolDirection != AudioManager.ADJUST_LOWER) { 1733 newRingerMode = RINGER_MODE_SILENT; 1734 } 1735 } else if (direction == AudioManager.ADJUST_RAISE) { 1736 newRingerMode = RINGER_MODE_NORMAL; 1737 } 1738 adjustVolumeIndex = false; 1739 } else { 1740 if (direction == AudioManager.ADJUST_RAISE) { 1741 // exiting silent mode 1742 // If VIBRATE_IN_SILENT, then go into vibrate mode 1743 newRingerMode = vibeInSilent ? RINGER_MODE_VIBRATE : RINGER_MODE_NORMAL; 1744 } 1745 adjustVolumeIndex = false; 1746 } 1747 1748 setRingerMode(newRingerMode); 1749 1750 mPrevVolDirection = direction; 1751 1752 return adjustVolumeIndex; 1753 } 1754 1755 public boolean isStreamAffectedByRingerMode(int streamType) { 1756 return (mRingerModeAffectedStreams & (1 << streamType)) != 0; 1757 } 1758 1759 private boolean isStreamMutedByRingerMode(int streamType) { 1760 return (mRingerModeMutedStreams & (1 << streamType)) != 0; 1761 } 1762 1763 public boolean isStreamAffectedByMute(int streamType) { 1764 return (mMuteAffectedStreams & (1 << streamType)) != 0; 1765 } 1766 1767 private void ensureValidDirection(int direction) { 1768 if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) { 1769 throw new IllegalArgumentException("Bad direction " + direction); 1770 } 1771 } 1772 1773 private void ensureValidStreamType(int streamType) { 1774 if (streamType < 0 || streamType >= mStreamStates.length) { 1775 throw new IllegalArgumentException("Bad stream type " + streamType); 1776 } 1777 } 1778 1779 private int getActiveStreamType(int suggestedStreamType) { 1780 1781 if (mVoiceCapable) { 1782 boolean isOffhook = false; 1783 try { 1784 ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); 1785 if (phone != null) isOffhook = phone.isOffhook(); 1786 } catch (RemoteException e) { 1787 Log.w(TAG, "Couldn't connect to phone service", e); 1788 } 1789 1790 if (isOffhook || getMode() == AudioManager.MODE_IN_COMMUNICATION) { 1791 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) 1792 == AudioSystem.FORCE_BT_SCO) { 1793 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO..."); 1794 return AudioSystem.STREAM_BLUETOOTH_SCO; 1795 } else { 1796 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL..."); 1797 return AudioSystem.STREAM_VOICE_CALL; 1798 } 1799 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) { 1800 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC..."); 1801 return AudioSystem.STREAM_MUSIC; 1802 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) { 1803 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING..." 1804 // + " b/c USE_DEFAULT_STREAM_TYPE..."); 1805 return AudioSystem.STREAM_RING; 1806 } else { 1807 // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType); 1808 return suggestedStreamType; 1809 } 1810 } else { 1811 if (getMode() == AudioManager.MODE_IN_COMMUNICATION) { 1812 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) 1813 == AudioSystem.FORCE_BT_SCO) { 1814 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO..."); 1815 return AudioSystem.STREAM_BLUETOOTH_SCO; 1816 } else { 1817 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL..."); 1818 return AudioSystem.STREAM_VOICE_CALL; 1819 } 1820 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION, 1821 NOTIFICATION_VOLUME_DELAY_MS) || 1822 AudioSystem.isStreamActive(AudioSystem.STREAM_RING, 1823 NOTIFICATION_VOLUME_DELAY_MS)) { 1824 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION..."); 1825 return AudioSystem.STREAM_NOTIFICATION; 1826 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0) || 1827 (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE)) { 1828 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC " 1829 // + " b/c USE_DEFAULT_STREAM_TYPE..."); 1830 return AudioSystem.STREAM_MUSIC; 1831 } else { 1832 // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType); 1833 return suggestedStreamType; 1834 } 1835 } 1836 } 1837 1838 private void broadcastRingerMode(int ringerMode) { 1839 // Send sticky broadcast 1840 Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION); 1841 broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, ringerMode); 1842 broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT 1843 | Intent.FLAG_RECEIVER_REPLACE_PENDING); 1844 long origCallerIdentityToken = Binder.clearCallingIdentity(); 1845 mContext.sendStickyBroadcast(broadcast); 1846 Binder.restoreCallingIdentity(origCallerIdentityToken); 1847 } 1848 1849 private void broadcastVibrateSetting(int vibrateType) { 1850 // Send broadcast 1851 if (ActivityManagerNative.isSystemReady()) { 1852 Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION); 1853 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType); 1854 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType)); 1855 mContext.sendBroadcast(broadcast); 1856 } 1857 } 1858 1859 // Message helper methods 1860 1861 private static void sendMsg(Handler handler, int msg, 1862 int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) { 1863 1864 if (existingMsgPolicy == SENDMSG_REPLACE) { 1865 handler.removeMessages(msg); 1866 } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { 1867 return; 1868 } 1869 1870 handler.sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay); 1871 } 1872 1873 boolean checkAudioSettingsPermission(String method) { 1874 if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS") 1875 == PackageManager.PERMISSION_GRANTED) { 1876 return true; 1877 } 1878 String msg = "Audio Settings Permission Denial: " + method + " from pid=" 1879 + Binder.getCallingPid() 1880 + ", uid=" + Binder.getCallingUid(); 1881 Log.w(TAG, msg); 1882 return false; 1883 } 1884 1885 private int getDeviceForStream(int stream) { 1886 int device = AudioSystem.getDevicesForStream(stream); 1887 if ((device & (device - 1)) != 0) { 1888 // Multiple device selection is either: 1889 // - speaker + one other device: give priority to speaker in this case. 1890 // - one A2DP device + another device: happens with duplicated output. In this case 1891 // retain the device on the A2DP output as the other must not correspond to an active 1892 // selection if not the speaker. 1893 if ((device & AudioSystem.DEVICE_OUT_SPEAKER) != 0) { 1894 device = AudioSystem.DEVICE_OUT_SPEAKER; 1895 } else { 1896 device &= AudioSystem.DEVICE_OUT_ALL_A2DP; 1897 } 1898 } 1899 return device; 1900 } 1901 1902 /////////////////////////////////////////////////////////////////////////// 1903 // Inner classes 1904 /////////////////////////////////////////////////////////////////////////// 1905 1906 public class VolumeStreamState { 1907 private final int mStreamType; 1908 1909 private String mVolumeIndexSettingName; 1910 private String mLastAudibleVolumeIndexSettingName; 1911 private int mIndexMax; 1912 private final HashMap <Integer, Integer> mIndex = new HashMap <Integer, Integer>(); 1913 private final HashMap <Integer, Integer> mLastAudibleIndex = 1914 new HashMap <Integer, Integer>(); 1915 private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo clients death 1916 1917 private VolumeStreamState(String settingName, int streamType) { 1918 1919 mVolumeIndexSettingName = settingName; 1920 mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; 1921 1922 mStreamType = streamType; 1923 mIndexMax = MAX_STREAM_VOLUME[streamType]; 1924 AudioSystem.initStreamVolume(streamType, 0, mIndexMax); 1925 mIndexMax *= 10; 1926 1927 readSettings(); 1928 1929 applyAllVolumes(); 1930 1931 mDeathHandlers = new ArrayList<VolumeDeathHandler>(); 1932 } 1933 1934 public String getSettingNameForDevice(boolean lastAudible, int device) { 1935 String name = lastAudible ? 1936 mLastAudibleVolumeIndexSettingName : 1937 mVolumeIndexSettingName; 1938 String suffix = AudioSystem.getDeviceName(device); 1939 if (suffix.isEmpty()) { 1940 return name; 1941 } 1942 return name + "_" + suffix; 1943 } 1944 1945 public void readSettings() { 1946 int index = Settings.System.getInt(mContentResolver, 1947 mVolumeIndexSettingName, 1948 AudioManager.DEFAULT_STREAM_VOLUME[mStreamType]); 1949 1950 mIndex.clear(); 1951 mIndex.put(AudioSystem.DEVICE_OUT_DEFAULT, index); 1952 1953 index = Settings.System.getInt(mContentResolver, 1954 mLastAudibleVolumeIndexSettingName, 1955 (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[mStreamType]); 1956 mLastAudibleIndex.clear(); 1957 mLastAudibleIndex.put(AudioSystem.DEVICE_OUT_DEFAULT, index); 1958 1959 int remainingDevices = AudioSystem.DEVICE_OUT_ALL; 1960 for (int i = 0; remainingDevices != 0; i++) { 1961 int device = (1 << i); 1962 if ((device & remainingDevices) == 0) { 1963 continue; 1964 } 1965 remainingDevices &= ~device; 1966 1967 // retrieve current volume for device 1968 String name = getSettingNameForDevice(false, device); 1969 index = Settings.System.getInt(mContentResolver, name, -1); 1970 if (index == -1) { 1971 continue; 1972 } 1973 mIndex.put(device, getValidIndex(10 * index)); 1974 1975 // retrieve last audible volume for device 1976 name = getSettingNameForDevice(true, device); 1977 index = Settings.System.getInt(mContentResolver, name, -1); 1978 mLastAudibleIndex.put(device, getValidIndex(10 * index)); 1979 } 1980 } 1981 1982 public void applyDeviceVolume(int device) { 1983 AudioSystem.setStreamVolumeIndex(mStreamType, 1984 (getIndex(device, false /* lastAudible */) + 5)/10, 1985 device); 1986 } 1987 1988 public void applyAllVolumes() { 1989 // apply default volume first: by convention this will reset all 1990 // devices volumes in audio policy manager to the supplied value 1991 AudioSystem.setStreamVolumeIndex(mStreamType, 1992 (getIndex(AudioSystem.DEVICE_OUT_DEFAULT, false /* lastAudible */) + 5)/10, 1993 AudioSystem.DEVICE_OUT_DEFAULT); 1994 // then apply device specific volumes 1995 Set set = mIndex.entrySet(); 1996 Iterator i = set.iterator(); 1997 while (i.hasNext()) { 1998 Map.Entry entry = (Map.Entry)i.next(); 1999 int device = ((Integer)entry.getKey()).intValue(); 2000 if (device != AudioSystem.DEVICE_OUT_DEFAULT) { 2001 AudioSystem.setStreamVolumeIndex(mStreamType, 2002 ((Integer)entry.getValue() + 5)/10, 2003 device); 2004 } 2005 } 2006 } 2007 2008 public boolean adjustIndex(int deltaIndex, int device) { 2009 return setIndex(getIndex(device, 2010 false /* lastAudible */) + deltaIndex * 10, 2011 device, 2012 true /* lastAudible */); 2013 } 2014 2015 public boolean setIndex(int index, int device, boolean lastAudible) { 2016 int oldIndex = getIndex(device, false /* lastAudible */); 2017 index = getValidIndex(index); 2018 mIndex.put(device, getValidIndex(index)); 2019 2020 if (oldIndex != index) { 2021 if (lastAudible) { 2022 mLastAudibleIndex.put(device, index); 2023 } 2024 // Apply change to all streams using this one as alias 2025 int numStreamTypes = AudioSystem.getNumStreamTypes(); 2026 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 2027 if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) { 2028 mStreamStates[streamType].setIndex(rescaleIndex(index, 2029 mStreamType, 2030 streamType), 2031 device, 2032 lastAudible); 2033 } 2034 } 2035 return true; 2036 } else { 2037 return false; 2038 } 2039 } 2040 2041 public int getIndex(int device, boolean lastAudible) { 2042 HashMap <Integer, Integer> indexes; 2043 if (lastAudible) { 2044 indexes = mLastAudibleIndex; 2045 } else { 2046 indexes = mIndex; 2047 } 2048 Integer index = indexes.get(device); 2049 if (index == null) { 2050 // there is always an entry for AudioSystem.DEVICE_OUT_DEFAULT 2051 index = indexes.get(AudioSystem.DEVICE_OUT_DEFAULT); 2052 } 2053 return index.intValue(); 2054 } 2055 2056 public void setLastAudibleIndex(int index, int device) { 2057 mLastAudibleIndex.put(device, getValidIndex(index)); 2058 } 2059 2060 public void adjustLastAudibleIndex(int deltaIndex, int device) { 2061 setLastAudibleIndex(getIndex(device, 2062 true /* lastAudible */) + deltaIndex * 10, 2063 device); 2064 } 2065 2066 public int getMaxIndex() { 2067 return mIndexMax; 2068 } 2069 2070 public void mute(IBinder cb, boolean state) { 2071 VolumeDeathHandler handler = getDeathHandler(cb, state); 2072 if (handler == null) { 2073 Log.e(TAG, "Could not get client death handler for stream: "+mStreamType); 2074 return; 2075 } 2076 handler.mute(state); 2077 } 2078 2079 private int getValidIndex(int index) { 2080 if (index < 0) { 2081 return 0; 2082 } else if (index > mIndexMax) { 2083 return mIndexMax; 2084 } 2085 2086 return index; 2087 } 2088 2089 private class VolumeDeathHandler implements IBinder.DeathRecipient { 2090 private IBinder mICallback; // To be notified of client's death 2091 private int mMuteCount; // Number of active mutes for this client 2092 2093 VolumeDeathHandler(IBinder cb) { 2094 mICallback = cb; 2095 } 2096 2097 public void mute(boolean state) { 2098 synchronized(mDeathHandlers) { 2099 if (state) { 2100 if (mMuteCount == 0) { 2101 // Register for client death notification 2102 try { 2103 // mICallback can be 0 if muted by AudioService 2104 if (mICallback != null) { 2105 mICallback.linkToDeath(this, 0); 2106 } 2107 mDeathHandlers.add(this); 2108 // If the stream is not yet muted by any client, set level to 0 2109 if (muteCount() == 0) { 2110 Set set = mIndex.entrySet(); 2111 Iterator i = set.iterator(); 2112 while (i.hasNext()) { 2113 Map.Entry entry = (Map.Entry)i.next(); 2114 int device = ((Integer)entry.getKey()).intValue(); 2115 setIndex(0, device, false /* lastAudible */); 2116 } 2117 sendMsg(mAudioHandler, 2118 MSG_SET_ALL_VOLUMES, 2119 SENDMSG_NOOP, 2120 0, 2121 0, 2122 VolumeStreamState.this, 0); 2123 } 2124 } catch (RemoteException e) { 2125 // Client has died! 2126 binderDied(); 2127 mDeathHandlers.notify(); 2128 return; 2129 } 2130 } else { 2131 Log.w(TAG, "stream: "+mStreamType+" was already muted by this client"); 2132 } 2133 mMuteCount++; 2134 } else { 2135 if (mMuteCount == 0) { 2136 Log.e(TAG, "unexpected unmute for stream: "+mStreamType); 2137 } else { 2138 mMuteCount--; 2139 if (mMuteCount == 0) { 2140 // Unregistr from client death notification 2141 mDeathHandlers.remove(this); 2142 // mICallback can be 0 if muted by AudioService 2143 if (mICallback != null) { 2144 mICallback.unlinkToDeath(this, 0); 2145 } 2146 if (muteCount() == 0) { 2147 // If the stream is not muted any more, restore it's volume if 2148 // ringer mode allows it 2149 if (!isStreamAffectedByRingerMode(mStreamType) || 2150 mRingerMode == AudioManager.RINGER_MODE_NORMAL) { 2151 Set set = mIndex.entrySet(); 2152 Iterator i = set.iterator(); 2153 while (i.hasNext()) { 2154 Map.Entry entry = (Map.Entry)i.next(); 2155 int device = ((Integer)entry.getKey()).intValue(); 2156 setIndex(getIndex(device, 2157 true /* lastAudible */), 2158 device, 2159 false /* lastAudible */); 2160 } 2161 sendMsg(mAudioHandler, 2162 MSG_SET_ALL_VOLUMES, 2163 SENDMSG_NOOP, 2164 0, 2165 0, 2166 VolumeStreamState.this, 0); 2167 } 2168 } 2169 } 2170 } 2171 } 2172 mDeathHandlers.notify(); 2173 } 2174 } 2175 2176 public void binderDied() { 2177 Log.w(TAG, "Volume service client died for stream: "+mStreamType); 2178 if (mMuteCount != 0) { 2179 // Reset all active mute requests from this client. 2180 mMuteCount = 1; 2181 mute(false); 2182 } 2183 } 2184 } 2185 2186 private int muteCount() { 2187 int count = 0; 2188 int size = mDeathHandlers.size(); 2189 for (int i = 0; i < size; i++) { 2190 count += mDeathHandlers.get(i).mMuteCount; 2191 } 2192 return count; 2193 } 2194 2195 private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) { 2196 synchronized(mDeathHandlers) { 2197 VolumeDeathHandler handler; 2198 int size = mDeathHandlers.size(); 2199 for (int i = 0; i < size; i++) { 2200 handler = mDeathHandlers.get(i); 2201 if (cb == handler.mICallback) { 2202 return handler; 2203 } 2204 } 2205 // If this is the first mute request for this client, create a new 2206 // client death handler. Otherwise, it is an out of sequence unmute request. 2207 if (state) { 2208 handler = new VolumeDeathHandler(cb); 2209 } else { 2210 Log.w(TAG, "stream was not muted by this client"); 2211 handler = null; 2212 } 2213 return handler; 2214 } 2215 } 2216 } 2217 2218 /** Thread that handles native AudioSystem control. */ 2219 private class AudioSystemThread extends Thread { 2220 AudioSystemThread() { 2221 super("AudioService"); 2222 } 2223 2224 @Override 2225 public void run() { 2226 // Set this thread up so the handler will work on it 2227 Looper.prepare(); 2228 2229 synchronized(AudioService.this) { 2230 mAudioHandler = new AudioHandler(); 2231 2232 // Notify that the handler has been created 2233 AudioService.this.notify(); 2234 } 2235 2236 // Listen for volume change requests that are set by VolumePanel 2237 Looper.loop(); 2238 } 2239 } 2240 2241 /** Handles internal volume messages in separate volume thread. */ 2242 private class AudioHandler extends Handler { 2243 2244 private void setDeviceVolume(VolumeStreamState streamState, int device) { 2245 2246 // Apply volume 2247 streamState.applyDeviceVolume(device); 2248 2249 // Apply change to all streams using this one as alias 2250 int numStreamTypes = AudioSystem.getNumStreamTypes(); 2251 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 2252 if (streamType != streamState.mStreamType && 2253 STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) { 2254 mStreamStates[streamType].applyDeviceVolume(device); 2255 } 2256 } 2257 2258 // Post a persist volume msg 2259 sendMsg(mAudioHandler, 2260 MSG_PERSIST_VOLUME, 2261 SENDMSG_REPLACE, 2262 PERSIST_CURRENT|PERSIST_LAST_AUDIBLE, 2263 device, 2264 streamState, 2265 PERSIST_DELAY); 2266 2267 } 2268 2269 private void setAllVolumes(VolumeStreamState streamState) { 2270 2271 // Apply volume 2272 streamState.applyAllVolumes(); 2273 2274 // Apply change to all streams using this one as alias 2275 int numStreamTypes = AudioSystem.getNumStreamTypes(); 2276 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 2277 if (streamType != streamState.mStreamType && 2278 STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) { 2279 mStreamStates[streamType].applyAllVolumes(); 2280 } 2281 } 2282 } 2283 2284 private void persistVolume(VolumeStreamState streamState, 2285 int persistType, 2286 int device) { 2287 if ((persistType & PERSIST_CURRENT) != 0) { 2288 System.putInt(mContentResolver, 2289 streamState.getSettingNameForDevice(false /* lastAudible */, device), 2290 (streamState.getIndex(device, false /* lastAudible */) + 5)/ 10); 2291 } 2292 if ((persistType & PERSIST_LAST_AUDIBLE) != 0) { 2293 System.putInt(mContentResolver, 2294 streamState.getSettingNameForDevice(true /* lastAudible */, device), 2295 (streamState.getIndex(device, true /* lastAudible */) + 5) / 10); 2296 } 2297 } 2298 2299 private void persistRingerMode(int ringerMode) { 2300 System.putInt(mContentResolver, System.MODE_RINGER, ringerMode); 2301 } 2302 2303 private void persistVibrateSetting() { 2304 System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting); 2305 } 2306 2307 private void playSoundEffect(int effectType, int volume) { 2308 synchronized (mSoundEffectsLock) { 2309 if (mSoundPool == null) { 2310 return; 2311 } 2312 float volFloat; 2313 // use default if volume is not specified by caller 2314 if (volume < 0) { 2315 volFloat = (float)Math.pow(10, SOUND_EFFECT_VOLUME_DB/20); 2316 } else { 2317 volFloat = (float) volume / 1000.0f; 2318 } 2319 2320 if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) { 2321 mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f); 2322 } else { 2323 MediaPlayer mediaPlayer = new MediaPlayer(); 2324 try { 2325 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]]; 2326 mediaPlayer.setDataSource(filePath); 2327 mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM); 2328 mediaPlayer.prepare(); 2329 mediaPlayer.setVolume(volFloat, volFloat); 2330 mediaPlayer.setOnCompletionListener(new OnCompletionListener() { 2331 public void onCompletion(MediaPlayer mp) { 2332 cleanupPlayer(mp); 2333 } 2334 }); 2335 mediaPlayer.setOnErrorListener(new OnErrorListener() { 2336 public boolean onError(MediaPlayer mp, int what, int extra) { 2337 cleanupPlayer(mp); 2338 return true; 2339 } 2340 }); 2341 mediaPlayer.start(); 2342 } catch (IOException ex) { 2343 Log.w(TAG, "MediaPlayer IOException: "+ex); 2344 } catch (IllegalArgumentException ex) { 2345 Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex); 2346 } catch (IllegalStateException ex) { 2347 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); 2348 } 2349 } 2350 } 2351 } 2352 2353 private void onHandlePersistMediaButtonReceiver(ComponentName receiver) { 2354 Settings.System.putString(mContentResolver, Settings.System.MEDIA_BUTTON_RECEIVER, 2355 receiver == null ? "" : receiver.flattenToString()); 2356 } 2357 2358 private void cleanupPlayer(MediaPlayer mp) { 2359 if (mp != null) { 2360 try { 2361 mp.stop(); 2362 mp.release(); 2363 } catch (IllegalStateException ex) { 2364 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); 2365 } 2366 } 2367 } 2368 2369 private void setForceUse(int usage, int config) { 2370 AudioSystem.setForceUse(usage, config); 2371 } 2372 2373 @Override 2374 public void handleMessage(Message msg) { 2375 2376 switch (msg.what) { 2377 2378 case MSG_SET_DEVICE_VOLUME: 2379 setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1); 2380 break; 2381 2382 case MSG_SET_ALL_VOLUMES: 2383 setAllVolumes((VolumeStreamState) msg.obj); 2384 break; 2385 2386 case MSG_PERSIST_VOLUME: 2387 persistVolume((VolumeStreamState) msg.obj, msg.arg1, msg.arg2); 2388 break; 2389 2390 case MSG_PERSIST_RINGER_MODE: 2391 // note that the value persisted is the current ringer mode, not the 2392 // value of ringer mode as of the time the request was made to persist 2393 persistRingerMode(getRingerMode()); 2394 break; 2395 2396 case MSG_PERSIST_VIBRATE_SETTING: 2397 persistVibrateSetting(); 2398 break; 2399 2400 case MSG_MEDIA_SERVER_DIED: 2401 if (!mMediaServerOk) { 2402 Log.e(TAG, "Media server died."); 2403 // Force creation of new IAudioFlinger interface so that we are notified 2404 // when new media_server process is back to life. 2405 AudioSystem.setErrorCallback(mAudioSystemCallback); 2406 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0, 2407 null, 500); 2408 } 2409 break; 2410 2411 case MSG_MEDIA_SERVER_STARTED: 2412 Log.e(TAG, "Media server started."); 2413 // indicate to audio HAL that we start the reconfiguration phase after a media 2414 // server crash 2415 // Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server 2416 // process restarts after a crash, not the first time it is started. 2417 AudioSystem.setParameters("restarting=true"); 2418 2419 // Restore device connection states 2420 synchronized (mConnectedDevices) { 2421 Set set = mConnectedDevices.entrySet(); 2422 Iterator i = set.iterator(); 2423 while (i.hasNext()) { 2424 Map.Entry device = (Map.Entry)i.next(); 2425 AudioSystem.setDeviceConnectionState( 2426 ((Integer)device.getKey()).intValue(), 2427 AudioSystem.DEVICE_STATE_AVAILABLE, 2428 (String)device.getValue()); 2429 } 2430 } 2431 // Restore call state 2432 AudioSystem.setPhoneState(mMode); 2433 2434 // Restore forced usage for communcations and record 2435 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm); 2436 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm); 2437 2438 // Restore stream volumes 2439 int numStreamTypes = AudioSystem.getNumStreamTypes(); 2440 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 2441 VolumeStreamState streamState = mStreamStates[streamType]; 2442 AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10); 2443 2444 streamState.applyAllVolumes(); 2445 } 2446 2447 // Restore ringer mode 2448 setRingerModeInt(getRingerMode(), false); 2449 2450 // indicate the end of reconfiguration phase to audio HAL 2451 AudioSystem.setParameters("restarting=false"); 2452 break; 2453 2454 case MSG_LOAD_SOUND_EFFECTS: 2455 loadSoundEffects(); 2456 break; 2457 2458 case MSG_PLAY_SOUND_EFFECT: 2459 playSoundEffect(msg.arg1, msg.arg2); 2460 break; 2461 2462 case MSG_BTA2DP_DOCK_TIMEOUT: 2463 // msg.obj == address of BTA2DP device 2464 synchronized (mConnectedDevices) { 2465 makeA2dpDeviceUnavailableNow( (String) msg.obj ); 2466 } 2467 break; 2468 2469 case MSG_SET_FORCE_USE: 2470 setForceUse(msg.arg1, msg.arg2); 2471 break; 2472 2473 case MSG_PERSIST_MEDIABUTTONRECEIVER: 2474 onHandlePersistMediaButtonReceiver( (ComponentName) msg.obj ); 2475 break; 2476 2477 case MSG_RCDISPLAY_CLEAR: 2478 onRcDisplayClear(); 2479 break; 2480 2481 case MSG_RCDISPLAY_UPDATE: 2482 // msg.obj is guaranteed to be non null 2483 onRcDisplayUpdate( (RemoteControlStackEntry) msg.obj, msg.arg1); 2484 break; 2485 2486 case MSG_BT_HEADSET_CNCT_FAILED: 2487 resetBluetoothSco(); 2488 break; 2489 } 2490 } 2491 } 2492 2493 private class SettingsObserver extends ContentObserver { 2494 2495 SettingsObserver() { 2496 super(new Handler()); 2497 mContentResolver.registerContentObserver(Settings.System.getUriFor( 2498 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this); 2499 } 2500 2501 @Override 2502 public void onChange(boolean selfChange) { 2503 super.onChange(selfChange); 2504 // FIXME This synchronized is not necessary if mSettingsLock only protects mRingerMode. 2505 // However there appear to be some missing locks around mRingerModeMutedStreams 2506 // and mRingerModeAffectedStreams, so will leave this synchronized for now. 2507 // mRingerModeMutedStreams and mMuteAffectedStreams are safe (only accessed once). 2508 synchronized (mSettingsLock) { 2509 int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver, 2510 Settings.System.MODE_RINGER_STREAMS_AFFECTED, 2511 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)| 2512 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED))); 2513 if (mVoiceCapable) { 2514 ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC); 2515 } else { 2516 ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC); 2517 } 2518 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) { 2519 /* 2520 * Ensure all stream types that should be affected by ringer mode 2521 * are in the proper state. 2522 */ 2523 mRingerModeAffectedStreams = ringerModeAffectedStreams; 2524 setRingerModeInt(getRingerMode(), false); 2525 } 2526 } 2527 } 2528 } 2529 2530 // must be called synchronized on mConnectedDevices 2531 private void makeA2dpDeviceAvailable(String address) { 2532 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 2533 AudioSystem.DEVICE_STATE_AVAILABLE, 2534 address); 2535 // Reset A2DP suspend state each time a new sink is connected 2536 AudioSystem.setParameters("A2dpSuspended=false"); 2537 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP), 2538 address); 2539 } 2540 2541 // must be called synchronized on mConnectedDevices 2542 private void makeA2dpDeviceUnavailableNow(String address) { 2543 Intent noisyIntent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY); 2544 mContext.sendBroadcast(noisyIntent); 2545 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 2546 AudioSystem.DEVICE_STATE_UNAVAILABLE, 2547 address); 2548 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP); 2549 } 2550 2551 // must be called synchronized on mConnectedDevices 2552 private void makeA2dpDeviceUnavailableLater(String address) { 2553 // prevent any activity on the A2DP audio output to avoid unwanted 2554 // reconnection of the sink. 2555 AudioSystem.setParameters("A2dpSuspended=true"); 2556 // the device will be made unavailable later, so consider it disconnected right away 2557 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP); 2558 // send the delayed message to make the device unavailable later 2559 Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address); 2560 mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS); 2561 2562 } 2563 2564 // must be called synchronized on mConnectedDevices 2565 private void cancelA2dpDeviceTimeout() { 2566 mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT); 2567 } 2568 2569 // must be called synchronized on mConnectedDevices 2570 private boolean hasScheduledA2dpDockTimeout() { 2571 return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT); 2572 } 2573 2574 private void handleA2dpConnectionStateChange(BluetoothDevice btDevice, int state) 2575 { 2576 if (btDevice == null) { 2577 return; 2578 } 2579 String address = btDevice.getAddress(); 2580 if (!BluetoothAdapter.checkBluetoothAddress(address)) { 2581 address = ""; 2582 } 2583 synchronized (mConnectedDevices) { 2584 boolean isConnected = 2585 (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) && 2586 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address)); 2587 2588 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) { 2589 if (btDevice.isBluetoothDock()) { 2590 if (state == BluetoothProfile.STATE_DISCONNECTED) { 2591 // introduction of a delay for transient disconnections of docks when 2592 // power is rapidly turned off/on, this message will be canceled if 2593 // we reconnect the dock under a preset delay 2594 makeA2dpDeviceUnavailableLater(address); 2595 // the next time isConnected is evaluated, it will be false for the dock 2596 } 2597 } else { 2598 makeA2dpDeviceUnavailableNow(address); 2599 } 2600 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) { 2601 if (btDevice.isBluetoothDock()) { 2602 // this could be a reconnection after a transient disconnection 2603 cancelA2dpDeviceTimeout(); 2604 mDockAddress = address; 2605 } else { 2606 // this could be a connection of another A2DP device before the timeout of 2607 // a dock: cancel the dock timeout, and make the dock unavailable now 2608 if(hasScheduledA2dpDockTimeout()) { 2609 cancelA2dpDeviceTimeout(); 2610 makeA2dpDeviceUnavailableNow(mDockAddress); 2611 } 2612 } 2613 makeA2dpDeviceAvailable(address); 2614 } 2615 } 2616 } 2617 2618 /* cache of the address of the last dock the device was connected to */ 2619 private String mDockAddress; 2620 2621 /** 2622 * Receiver for misc intent broadcasts the Phone app cares about. 2623 */ 2624 private class AudioServiceBroadcastReceiver extends BroadcastReceiver { 2625 @Override 2626 public void onReceive(Context context, Intent intent) { 2627 String action = intent.getAction(); 2628 2629 if (action.equals(Intent.ACTION_DOCK_EVENT)) { 2630 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 2631 Intent.EXTRA_DOCK_STATE_UNDOCKED); 2632 int config; 2633 switch (dockState) { 2634 case Intent.EXTRA_DOCK_STATE_DESK: 2635 config = AudioSystem.FORCE_BT_DESK_DOCK; 2636 break; 2637 case Intent.EXTRA_DOCK_STATE_CAR: 2638 config = AudioSystem.FORCE_BT_CAR_DOCK; 2639 break; 2640 case Intent.EXTRA_DOCK_STATE_LE_DESK: 2641 config = AudioSystem.FORCE_ANALOG_DOCK; 2642 break; 2643 case Intent.EXTRA_DOCK_STATE_HE_DESK: 2644 config = AudioSystem.FORCE_DIGITAL_DOCK; 2645 break; 2646 case Intent.EXTRA_DOCK_STATE_UNDOCKED: 2647 default: 2648 config = AudioSystem.FORCE_NONE; 2649 } 2650 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config); 2651 } else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) { 2652 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, 2653 BluetoothProfile.STATE_DISCONNECTED); 2654 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 2655 2656 handleA2dpConnectionStateChange(btDevice, state); 2657 } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) { 2658 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, 2659 BluetoothProfile.STATE_DISCONNECTED); 2660 int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO; 2661 String address = null; 2662 2663 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 2664 if (btDevice == null) { 2665 return; 2666 } 2667 2668 address = btDevice.getAddress(); 2669 BluetoothClass btClass = btDevice.getBluetoothClass(); 2670 if (btClass != null) { 2671 switch (btClass.getDeviceClass()) { 2672 case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET: 2673 case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE: 2674 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 2675 break; 2676 case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO: 2677 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 2678 break; 2679 } 2680 } 2681 2682 if (!BluetoothAdapter.checkBluetoothAddress(address)) { 2683 address = ""; 2684 } 2685 2686 synchronized (mConnectedDevices) { 2687 boolean isConnected = (mConnectedDevices.containsKey(device) && 2688 mConnectedDevices.get(device).equals(address)); 2689 2690 synchronized (mScoClients) { 2691 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) { 2692 AudioSystem.setDeviceConnectionState(device, 2693 AudioSystem.DEVICE_STATE_UNAVAILABLE, 2694 address); 2695 mConnectedDevices.remove(device); 2696 mBluetoothHeadsetDevice = null; 2697 resetBluetoothSco(); 2698 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) { 2699 AudioSystem.setDeviceConnectionState(device, 2700 AudioSystem.DEVICE_STATE_AVAILABLE, 2701 address); 2702 mConnectedDevices.put(new Integer(device), address); 2703 mBluetoothHeadsetDevice = btDevice; 2704 } 2705 } 2706 } 2707 } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { 2708 int state = intent.getIntExtra("state", 0); 2709 int microphone = intent.getIntExtra("microphone", 0); 2710 2711 synchronized (mConnectedDevices) { 2712 if (microphone != 0) { 2713 boolean isConnected = 2714 mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET); 2715 if (state == 0 && isConnected) { 2716 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET, 2717 AudioSystem.DEVICE_STATE_UNAVAILABLE, 2718 ""); 2719 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET); 2720 } else if (state == 1 && !isConnected) { 2721 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET, 2722 AudioSystem.DEVICE_STATE_AVAILABLE, 2723 ""); 2724 mConnectedDevices.put( 2725 new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), ""); 2726 } 2727 } else { 2728 boolean isConnected = 2729 mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE); 2730 if (state == 0 && isConnected) { 2731 AudioSystem.setDeviceConnectionState( 2732 AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, 2733 AudioSystem.DEVICE_STATE_UNAVAILABLE, 2734 ""); 2735 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE); 2736 } else if (state == 1 && !isConnected) { 2737 AudioSystem.setDeviceConnectionState( 2738 AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, 2739 AudioSystem.DEVICE_STATE_AVAILABLE, 2740 ""); 2741 mConnectedDevices.put( 2742 new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), ""); 2743 } 2744 } 2745 } 2746 } else if (action.equals(Intent.ACTION_USB_ANLG_HEADSET_PLUG)) { 2747 int state = intent.getIntExtra("state", 0); 2748 Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_ANLG_HEADSET_PLUG, state = "+state); 2749 synchronized (mConnectedDevices) { 2750 boolean isConnected = 2751 mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET); 2752 if (state == 0 && isConnected) { 2753 AudioSystem.setDeviceConnectionState( 2754 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET, 2755 AudioSystem.DEVICE_STATE_UNAVAILABLE, 2756 ""); 2757 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET); 2758 } else if (state == 1 && !isConnected) { 2759 AudioSystem.setDeviceConnectionState( 2760 AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET, 2761 AudioSystem.DEVICE_STATE_AVAILABLE, 2762 ""); 2763 mConnectedDevices.put( 2764 new Integer(AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET), ""); 2765 } 2766 } 2767 } else if (action.equals(Intent.ACTION_HDMI_AUDIO_PLUG)) { 2768 int state = intent.getIntExtra("state", 0); 2769 Log.v(TAG, "Broadcast Receiver: Got ACTION_HDMI_AUDIO_PLUG, state = "+state); 2770 synchronized (mConnectedDevices) { 2771 boolean isConnected = 2772 mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_AUX_DIGITAL); 2773 if (state == 0 && isConnected) { 2774 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL, 2775 AudioSystem.DEVICE_STATE_UNAVAILABLE, 2776 ""); 2777 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_AUX_DIGITAL); 2778 } else if (state == 1 && !isConnected) { 2779 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_AUX_DIGITAL, 2780 AudioSystem.DEVICE_STATE_AVAILABLE, 2781 ""); 2782 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_AUX_DIGITAL), ""); 2783 } 2784 } 2785 } else if (action.equals(Intent.ACTION_USB_DGTL_HEADSET_PLUG)) { 2786 int state = intent.getIntExtra("state", 0); 2787 Log.v(TAG, "Broadcast Receiver: Got ACTION_USB_DGTL_HEADSET_PLUG, state = "+state); 2788 synchronized (mConnectedDevices) { 2789 boolean isConnected = 2790 mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET); 2791 if (state == 0 && isConnected) { 2792 AudioSystem.setDeviceConnectionState( 2793 AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET, 2794 AudioSystem.DEVICE_STATE_UNAVAILABLE, 2795 ""); 2796 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET); 2797 } else if (state == 1 && !isConnected) { 2798 AudioSystem.setDeviceConnectionState( 2799 AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET, 2800 AudioSystem.DEVICE_STATE_AVAILABLE, 2801 ""); 2802 mConnectedDevices.put( 2803 new Integer(AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET), ""); 2804 } 2805 } 2806 } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) { 2807 boolean broadcast = false; 2808 int state = AudioManager.SCO_AUDIO_STATE_ERROR; 2809 synchronized (mScoClients) { 2810 int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1); 2811 // broadcast intent if the connection was initated by AudioService 2812 if (!mScoClients.isEmpty() && 2813 (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL || 2814 mScoAudioState == SCO_STATE_ACTIVATE_REQ || 2815 mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) { 2816 broadcast = true; 2817 } 2818 switch (btState) { 2819 case BluetoothHeadset.STATE_AUDIO_CONNECTED: 2820 state = AudioManager.SCO_AUDIO_STATE_CONNECTED; 2821 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL && 2822 mScoAudioState != SCO_STATE_DEACTIVATE_REQ && 2823 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) { 2824 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL; 2825 } 2826 break; 2827 case BluetoothHeadset.STATE_AUDIO_DISCONNECTED: 2828 state = AudioManager.SCO_AUDIO_STATE_DISCONNECTED; 2829 mScoAudioState = SCO_STATE_INACTIVE; 2830 clearAllScoClients(0, false); 2831 break; 2832 case BluetoothHeadset.STATE_AUDIO_CONNECTING: 2833 if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL && 2834 mScoAudioState != SCO_STATE_DEACTIVATE_REQ && 2835 mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) { 2836 mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL; 2837 } 2838 default: 2839 // do not broadcast CONNECTING or invalid state 2840 broadcast = false; 2841 break; 2842 } 2843 } 2844 if (broadcast) { 2845 broadcastScoConnectionState(state); 2846 //FIXME: this is to maintain compatibility with deprecated intent 2847 // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate. 2848 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); 2849 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state); 2850 mContext.sendStickyBroadcast(newIntent); 2851 } 2852 } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { 2853 mBootCompleted = true; 2854 sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_NOOP, 2855 0, 0, null, 0); 2856 2857 mKeyguardManager = 2858 (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE); 2859 mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR; 2860 resetBluetoothSco(); 2861 getBluetoothHeadset(); 2862 //FIXME: this is to maintain compatibility with deprecated intent 2863 // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate. 2864 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); 2865 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, 2866 AudioManager.SCO_AUDIO_STATE_DISCONNECTED); 2867 mContext.sendStickyBroadcast(newIntent); 2868 2869 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); 2870 if (adapter != null) { 2871 adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener, 2872 BluetoothProfile.A2DP); 2873 } 2874 } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) { 2875 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 2876 // a package is being removed, not replaced 2877 String packageName = intent.getData().getSchemeSpecificPart(); 2878 if (packageName != null) { 2879 removeMediaButtonReceiverForPackage(packageName); 2880 } 2881 } 2882 } else if (action.equals(Intent.ACTION_SCREEN_ON)) { 2883 AudioSystem.setParameters("screen_state=on"); 2884 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { 2885 AudioSystem.setParameters("screen_state=off"); 2886 } 2887 } 2888 } 2889 2890 //========================================================================================== 2891 // AudioFocus 2892 //========================================================================================== 2893 2894 /* constant to identify focus stack entry that is used to hold the focus while the phone 2895 * is ringing or during a call. Used by com.android.internal.telephony.CallManager when 2896 * entering and exiting calls. 2897 */ 2898 public final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls"; 2899 2900 private final static Object mAudioFocusLock = new Object(); 2901 2902 private final static Object mRingingLock = new Object(); 2903 2904 private PhoneStateListener mPhoneStateListener = new PhoneStateListener() { 2905 @Override 2906 public void onCallStateChanged(int state, String incomingNumber) { 2907 if (state == TelephonyManager.CALL_STATE_RINGING) { 2908 //Log.v(TAG, " CALL_STATE_RINGING"); 2909 synchronized(mRingingLock) { 2910 mIsRinging = true; 2911 } 2912 } else if ((state == TelephonyManager.CALL_STATE_OFFHOOK) 2913 || (state == TelephonyManager.CALL_STATE_IDLE)) { 2914 synchronized(mRingingLock) { 2915 mIsRinging = false; 2916 } 2917 } 2918 } 2919 }; 2920 2921 private void notifyTopOfAudioFocusStack() { 2922 // notify the top of the stack it gained focus 2923 if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) { 2924 if (canReassignAudioFocus()) { 2925 try { 2926 mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange( 2927 AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId); 2928 } catch (RemoteException e) { 2929 Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e); 2930 e.printStackTrace(); 2931 } 2932 } 2933 } 2934 } 2935 2936 private static class FocusStackEntry { 2937 public int mStreamType = -1;// no stream type 2938 public IAudioFocusDispatcher mFocusDispatcher = null; 2939 public IBinder mSourceRef = null; 2940 public String mClientId; 2941 public int mFocusChangeType; 2942 public AudioFocusDeathHandler mHandler; 2943 public String mPackageName; 2944 public int mCallingUid; 2945 2946 public FocusStackEntry() { 2947 } 2948 2949 public FocusStackEntry(int streamType, int duration, 2950 IAudioFocusDispatcher afl, IBinder source, String id, AudioFocusDeathHandler hdlr, 2951 String pn, int uid) { 2952 mStreamType = streamType; 2953 mFocusDispatcher = afl; 2954 mSourceRef = source; 2955 mClientId = id; 2956 mFocusChangeType = duration; 2957 mHandler = hdlr; 2958 mPackageName = pn; 2959 mCallingUid = uid; 2960 } 2961 2962 public void unlinkToDeath() { 2963 try { 2964 if (mSourceRef != null && mHandler != null) { 2965 mSourceRef.unlinkToDeath(mHandler, 0); 2966 mHandler = null; 2967 } 2968 } catch (java.util.NoSuchElementException e) { 2969 Log.e(TAG, "Encountered " + e + " in FocusStackEntry.unlinkToDeath()"); 2970 } 2971 } 2972 2973 @Override 2974 protected void finalize() throws Throwable { 2975 unlinkToDeath(); // unlink exception handled inside method 2976 super.finalize(); 2977 } 2978 } 2979 2980 private final Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>(); 2981 2982 /** 2983 * Helper function: 2984 * Display in the log the current entries in the audio focus stack 2985 */ 2986 private void dumpFocusStack(PrintWriter pw) { 2987 pw.println("\nAudio Focus stack entries:"); 2988 synchronized(mAudioFocusLock) { 2989 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); 2990 while(stackIterator.hasNext()) { 2991 FocusStackEntry fse = stackIterator.next(); 2992 pw.println(" source:" + fse.mSourceRef + " -- client: " + fse.mClientId 2993 + " -- duration: " + fse.mFocusChangeType 2994 + " -- uid: " + fse.mCallingUid); 2995 } 2996 } 2997 } 2998 2999 /** 3000 * Helper function: 3001 * Called synchronized on mAudioFocusLock 3002 * Remove a focus listener from the focus stack. 3003 * @param focusListenerToRemove the focus listener 3004 * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding 3005 * focus, notify the next item in the stack it gained focus. 3006 */ 3007 private void removeFocusStackEntry(String clientToRemove, boolean signal) { 3008 // is the current top of the focus stack abandoning focus? (because of request, not death) 3009 if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove)) 3010 { 3011 //Log.i(TAG, " removeFocusStackEntry() removing top of stack"); 3012 FocusStackEntry fse = mFocusStack.pop(); 3013 fse.unlinkToDeath(); 3014 if (signal) { 3015 // notify the new top of the stack it gained focus 3016 notifyTopOfAudioFocusStack(); 3017 // there's a new top of the stack, let the remote control know 3018 synchronized(mRCStack) { 3019 checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); 3020 } 3021 } 3022 } else { 3023 // focus is abandoned by a client that's not at the top of the stack, 3024 // no need to update focus. 3025 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); 3026 while(stackIterator.hasNext()) { 3027 FocusStackEntry fse = (FocusStackEntry)stackIterator.next(); 3028 if(fse.mClientId.equals(clientToRemove)) { 3029 Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for " 3030 + fse.mClientId); 3031 stackIterator.remove(); 3032 fse.unlinkToDeath(); 3033 } 3034 } 3035 } 3036 } 3037 3038 /** 3039 * Helper function: 3040 * Called synchronized on mAudioFocusLock 3041 * Remove focus listeners from the focus stack for a particular client when it has died. 3042 */ 3043 private void removeFocusStackEntryForClient(IBinder cb) { 3044 // is the owner of the audio focus part of the client to remove? 3045 boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() && 3046 mFocusStack.peek().mSourceRef.equals(cb); 3047 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); 3048 while(stackIterator.hasNext()) { 3049 FocusStackEntry fse = (FocusStackEntry)stackIterator.next(); 3050 if(fse.mSourceRef.equals(cb)) { 3051 Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for " 3052 + fse.mClientId); 3053 stackIterator.remove(); 3054 // the client just died, no need to unlink to its death 3055 } 3056 } 3057 if (isTopOfStackForClientToRemove) { 3058 // we removed an entry at the top of the stack: 3059 // notify the new top of the stack it gained focus. 3060 notifyTopOfAudioFocusStack(); 3061 // there's a new top of the stack, let the remote control know 3062 synchronized(mRCStack) { 3063 checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); 3064 } 3065 } 3066 } 3067 3068 /** 3069 * Helper function: 3070 * Returns true if the system is in a state where the focus can be reevaluated, false otherwise. 3071 */ 3072 private boolean canReassignAudioFocus() { 3073 // focus requests are rejected during a phone call or when the phone is ringing 3074 // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus 3075 if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) { 3076 return false; 3077 } 3078 return true; 3079 } 3080 3081 /** 3082 * Inner class to monitor audio focus client deaths, and remove them from the audio focus 3083 * stack if necessary. 3084 */ 3085 private class AudioFocusDeathHandler implements IBinder.DeathRecipient { 3086 private IBinder mCb; // To be notified of client's death 3087 3088 AudioFocusDeathHandler(IBinder cb) { 3089 mCb = cb; 3090 } 3091 3092 public void binderDied() { 3093 synchronized(mAudioFocusLock) { 3094 Log.w(TAG, " AudioFocus audio focus client died"); 3095 removeFocusStackEntryForClient(mCb); 3096 } 3097 } 3098 3099 public IBinder getBinder() { 3100 return mCb; 3101 } 3102 } 3103 3104 3105 /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */ 3106 public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb, 3107 IAudioFocusDispatcher fd, String clientId, String callingPackageName) { 3108 Log.i(TAG, " AudioFocus requestAudioFocus() from " + clientId); 3109 // the main stream type for the audio focus request is currently not used. It may 3110 // potentially be used to handle multiple stream type-dependent audio focuses. 3111 3112 // we need a valid binder callback for clients 3113 if (!cb.pingBinder()) { 3114 Log.e(TAG, " AudioFocus DOA client for requestAudioFocus(), aborting."); 3115 return AudioManager.AUDIOFOCUS_REQUEST_FAILED; 3116 } 3117 3118 synchronized(mAudioFocusLock) { 3119 if (!canReassignAudioFocus()) { 3120 return AudioManager.AUDIOFOCUS_REQUEST_FAILED; 3121 } 3122 3123 // handle the potential premature death of the new holder of the focus 3124 // (premature death == death before abandoning focus) 3125 // Register for client death notification 3126 AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb); 3127 try { 3128 cb.linkToDeath(afdh, 0); 3129 } catch (RemoteException e) { 3130 // client has already died! 3131 Log.w(TAG, "AudioFocus requestAudioFocus() could not link to "+cb+" binder death"); 3132 return AudioManager.AUDIOFOCUS_REQUEST_FAILED; 3133 } 3134 3135 if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) { 3136 // if focus is already owned by this client and the reason for acquiring the focus 3137 // hasn't changed, don't do anything 3138 if (mFocusStack.peek().mFocusChangeType == focusChangeHint) { 3139 // unlink death handler so it can be gc'ed. 3140 // linkToDeath() creates a JNI global reference preventing collection. 3141 cb.unlinkToDeath(afdh, 0); 3142 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; 3143 } 3144 // the reason for the audio focus request has changed: remove the current top of 3145 // stack and respond as if we had a new focus owner 3146 FocusStackEntry fse = mFocusStack.pop(); 3147 fse.unlinkToDeath(); 3148 } 3149 3150 // notify current top of stack it is losing focus 3151 if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) { 3152 try { 3153 mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange( 3154 -1 * focusChangeHint, // loss and gain codes are inverse of each other 3155 mFocusStack.peek().mClientId); 3156 } catch (RemoteException e) { 3157 Log.e(TAG, " Failure to signal loss of focus due to "+ e); 3158 e.printStackTrace(); 3159 } 3160 } 3161 3162 // focus requester might already be somewhere below in the stack, remove it 3163 removeFocusStackEntry(clientId, false /* signal */); 3164 3165 // push focus requester at the top of the audio focus stack 3166 mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, fd, cb, 3167 clientId, afdh, callingPackageName, Binder.getCallingUid())); 3168 3169 // there's a new top of the stack, let the remote control know 3170 synchronized(mRCStack) { 3171 checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); 3172 } 3173 }//synchronized(mAudioFocusLock) 3174 3175 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; 3176 } 3177 3178 /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */ 3179 public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) { 3180 Log.i(TAG, " AudioFocus abandonAudioFocus() from " + clientId); 3181 try { 3182 // this will take care of notifying the new focus owner if needed 3183 synchronized(mAudioFocusLock) { 3184 removeFocusStackEntry(clientId, true); 3185 } 3186 } catch (java.util.ConcurrentModificationException cme) { 3187 // Catching this exception here is temporary. It is here just to prevent 3188 // a crash seen when the "Silent" notification is played. This is believed to be fixed 3189 // but this try catch block is left just to be safe. 3190 Log.e(TAG, "FATAL EXCEPTION AudioFocus abandonAudioFocus() caused " + cme); 3191 cme.printStackTrace(); 3192 } 3193 3194 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; 3195 } 3196 3197 3198 public void unregisterAudioFocusClient(String clientId) { 3199 synchronized(mAudioFocusLock) { 3200 removeFocusStackEntry(clientId, false); 3201 } 3202 } 3203 3204 3205 //========================================================================================== 3206 // RemoteControl 3207 //========================================================================================== 3208 /** 3209 * Receiver for media button intents. Handles the dispatching of the media button event 3210 * to one of the registered listeners, or if there was none, resumes the intent broadcast 3211 * to the rest of the system. 3212 */ 3213 private class MediaButtonBroadcastReceiver extends BroadcastReceiver { 3214 @Override 3215 public void onReceive(Context context, Intent intent) { 3216 String action = intent.getAction(); 3217 if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) { 3218 return; 3219 } 3220 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); 3221 if (event != null) { 3222 // if in a call or ringing, do not break the current phone app behavior 3223 // TODO modify this to let the phone app specifically get the RC focus 3224 // add modify the phone app to take advantage of the new API 3225 synchronized(mRingingLock) { 3226 if (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL) || 3227 (getMode() == AudioSystem.MODE_IN_COMMUNICATION) || 3228 (getMode() == AudioSystem.MODE_RINGTONE) ) { 3229 return; 3230 } 3231 } 3232 synchronized(mRCStack) { 3233 if (!mRCStack.empty()) { 3234 // create a new intent to fill in the extras of the registered PendingIntent 3235 Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); 3236 Bundle extras = intent.getExtras(); 3237 if (extras != null) { 3238 targetedIntent.putExtras(extras); 3239 // trap the current broadcast 3240 abortBroadcast(); 3241 //Log.v(TAG, " Sending intent" + targetedIntent); 3242 // send the intent that was registered by the client 3243 try { 3244 mRCStack.peek().mMediaIntent.send(context, 0, targetedIntent); 3245 } catch (CanceledException e) { 3246 Log.e(TAG, "Error sending pending intent " + mRCStack.peek()); 3247 e.printStackTrace(); 3248 } 3249 } 3250 } 3251 } 3252 } 3253 } 3254 } 3255 3256 private final Object mCurrentRcLock = new Object(); 3257 /** 3258 * The one remote control client which will receive a request for display information. 3259 * This object may be null. 3260 * Access protected by mCurrentRcLock. 3261 */ 3262 private IRemoteControlClient mCurrentRcClient = null; 3263 3264 private final static int RC_INFO_NONE = 0; 3265 private final static int RC_INFO_ALL = 3266 RemoteControlClient.FLAG_INFORMATION_REQUEST_ALBUM_ART | 3267 RemoteControlClient.FLAG_INFORMATION_REQUEST_KEY_MEDIA | 3268 RemoteControlClient.FLAG_INFORMATION_REQUEST_METADATA | 3269 RemoteControlClient.FLAG_INFORMATION_REQUEST_PLAYSTATE; 3270 3271 /** 3272 * A monotonically increasing generation counter for mCurrentRcClient. 3273 * Only accessed with a lock on mCurrentRcLock. 3274 * No value wrap-around issues as we only act on equal values. 3275 */ 3276 private int mCurrentRcClientGen = 0; 3277 3278 /** 3279 * Inner class to monitor remote control client deaths, and remove the client for the 3280 * remote control stack if necessary. 3281 */ 3282 private class RcClientDeathHandler implements IBinder.DeathRecipient { 3283 private IBinder mCb; // To be notified of client's death 3284 private PendingIntent mMediaIntent; 3285 3286 RcClientDeathHandler(IBinder cb, PendingIntent pi) { 3287 mCb = cb; 3288 mMediaIntent = pi; 3289 } 3290 3291 public void binderDied() { 3292 Log.w(TAG, " RemoteControlClient died"); 3293 // remote control client died, make sure the displays don't use it anymore 3294 // by setting its remote control client to null 3295 registerRemoteControlClient(mMediaIntent, null/*rcClient*/, null/*ignored*/); 3296 } 3297 3298 public IBinder getBinder() { 3299 return mCb; 3300 } 3301 } 3302 3303 private static class RemoteControlStackEntry { 3304 /** 3305 * The target for the ACTION_MEDIA_BUTTON events. 3306 * Always non null. 3307 */ 3308 public PendingIntent mMediaIntent; 3309 /** 3310 * The registered media button event receiver. 3311 * Always non null. 3312 */ 3313 public ComponentName mReceiverComponent; 3314 public String mCallingPackageName; 3315 public int mCallingUid; 3316 /** 3317 * Provides access to the information to display on the remote control. 3318 * May be null (when a media button event receiver is registered, 3319 * but no remote control client has been registered) */ 3320 public IRemoteControlClient mRcClient; 3321 public RcClientDeathHandler mRcClientDeathHandler; 3322 3323 /** precondition: mediaIntent != null, eventReceiver != null */ 3324 public RemoteControlStackEntry(PendingIntent mediaIntent, ComponentName eventReceiver) { 3325 mMediaIntent = mediaIntent; 3326 mReceiverComponent = eventReceiver; 3327 mCallingUid = -1; 3328 mRcClient = null; 3329 } 3330 3331 public void unlinkToRcClientDeath() { 3332 if ((mRcClientDeathHandler != null) && (mRcClientDeathHandler.mCb != null)) { 3333 try { 3334 mRcClientDeathHandler.mCb.unlinkToDeath(mRcClientDeathHandler, 0); 3335 mRcClientDeathHandler = null; 3336 } catch (java.util.NoSuchElementException e) { 3337 // not much we can do here 3338 Log.e(TAG, "Encountered " + e + " in unlinkToRcClientDeath()"); 3339 e.printStackTrace(); 3340 } 3341 } 3342 } 3343 3344 @Override 3345 protected void finalize() throws Throwable { 3346 unlinkToRcClientDeath();// unlink exception handled inside method 3347 super.finalize(); 3348 } 3349 } 3350 3351 /** 3352 * The stack of remote control event receivers. 3353 * Code sections and methods that modify the remote control event receiver stack are 3354 * synchronized on mRCStack, but also BEFORE on mFocusLock as any change in either 3355 * stack, audio focus or RC, can lead to a change in the remote control display 3356 */ 3357 private final Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>(); 3358 3359 /** 3360 * Helper function: 3361 * Display in the log the current entries in the remote control focus stack 3362 */ 3363 private void dumpRCStack(PrintWriter pw) { 3364 pw.println("\nRemote Control stack entries:"); 3365 synchronized(mRCStack) { 3366 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3367 while(stackIterator.hasNext()) { 3368 RemoteControlStackEntry rcse = stackIterator.next(); 3369 pw.println(" pi: " + rcse.mMediaIntent + 3370 " -- ercvr: " + rcse.mReceiverComponent + 3371 " -- client: " + rcse.mRcClient + 3372 " -- uid: " + rcse.mCallingUid); 3373 } 3374 } 3375 } 3376 3377 /** 3378 * Helper function: 3379 * Remove any entry in the remote control stack that has the same package name as packageName 3380 * Pre-condition: packageName != null 3381 */ 3382 private void removeMediaButtonReceiverForPackage(String packageName) { 3383 synchronized(mRCStack) { 3384 if (mRCStack.empty()) { 3385 return; 3386 } else { 3387 RemoteControlStackEntry oldTop = mRCStack.peek(); 3388 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3389 // iterate over the stack entries 3390 while(stackIterator.hasNext()) { 3391 RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next(); 3392 if (packageName.equalsIgnoreCase(rcse.mReceiverComponent.getPackageName())) { 3393 // a stack entry is from the package being removed, remove it from the stack 3394 stackIterator.remove(); 3395 rcse.unlinkToRcClientDeath(); 3396 } 3397 } 3398 if (mRCStack.empty()) { 3399 // no saved media button receiver 3400 mAudioHandler.sendMessage( 3401 mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, 3402 null)); 3403 } else if (oldTop != mRCStack.peek()) { 3404 // the top of the stack has changed, save it in the system settings 3405 // by posting a message to persist it 3406 mAudioHandler.sendMessage( 3407 mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, 3408 mRCStack.peek().mReceiverComponent)); 3409 } 3410 } 3411 } 3412 } 3413 3414 /** 3415 * Helper function: 3416 * Restore remote control receiver from the system settings. 3417 */ 3418 private void restoreMediaButtonReceiver() { 3419 String receiverName = Settings.System.getString(mContentResolver, 3420 Settings.System.MEDIA_BUTTON_RECEIVER); 3421 if ((null != receiverName) && !receiverName.isEmpty()) { 3422 ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName); 3423 // construct a PendingIntent targeted to the restored component name 3424 // for the media button and register it 3425 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); 3426 // the associated intent will be handled by the component being registered 3427 mediaButtonIntent.setComponent(eventReceiver); 3428 PendingIntent pi = PendingIntent.getBroadcast(mContext, 3429 0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/); 3430 registerMediaButtonIntent(pi, eventReceiver); 3431 } 3432 } 3433 3434 /** 3435 * Helper function: 3436 * Set the new remote control receiver at the top of the RC focus stack. 3437 * precondition: mediaIntent != null, target != null 3438 */ 3439 private void pushMediaButtonReceiver(PendingIntent mediaIntent, ComponentName target) { 3440 // already at top of stack? 3441 if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(mediaIntent)) { 3442 return; 3443 } 3444 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3445 RemoteControlStackEntry rcse = null; 3446 boolean wasInsideStack = false; 3447 while(stackIterator.hasNext()) { 3448 rcse = (RemoteControlStackEntry)stackIterator.next(); 3449 if(rcse.mMediaIntent.equals(mediaIntent)) { 3450 wasInsideStack = true; 3451 stackIterator.remove(); 3452 break; 3453 } 3454 } 3455 if (!wasInsideStack) { 3456 rcse = new RemoteControlStackEntry(mediaIntent, target); 3457 } 3458 mRCStack.push(rcse); 3459 3460 // post message to persist the default media button receiver 3461 mAudioHandler.sendMessage( mAudioHandler.obtainMessage( 3462 MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, target/*obj*/) ); 3463 } 3464 3465 /** 3466 * Helper function: 3467 * Remove the remote control receiver from the RC focus stack. 3468 * precondition: pi != null 3469 */ 3470 private void removeMediaButtonReceiver(PendingIntent pi) { 3471 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3472 while(stackIterator.hasNext()) { 3473 RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next(); 3474 if(rcse.mMediaIntent.equals(pi)) { 3475 stackIterator.remove(); 3476 rcse.unlinkToRcClientDeath(); 3477 break; 3478 } 3479 } 3480 } 3481 3482 /** 3483 * Helper function: 3484 * Called synchronized on mRCStack 3485 */ 3486 private boolean isCurrentRcController(PendingIntent pi) { 3487 if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(pi)) { 3488 return true; 3489 } 3490 return false; 3491 } 3492 3493 //========================================================================================== 3494 // Remote control display / client 3495 //========================================================================================== 3496 /** 3497 * Update the remote control displays with the new "focused" client generation 3498 */ 3499 private void setNewRcClientOnDisplays_syncRcsCurrc(int newClientGeneration, 3500 PendingIntent newMediaIntent, boolean clearing) { 3501 // NOTE: Only one IRemoteControlDisplay supported in this implementation 3502 if (mRcDisplay != null) { 3503 try { 3504 mRcDisplay.setCurrentClientId( 3505 newClientGeneration, newMediaIntent, clearing); 3506 } catch (RemoteException e) { 3507 Log.e(TAG, "Dead display in setNewRcClientOnDisplays_syncRcsCurrc() "+e); 3508 // if we had a display before, stop monitoring its death 3509 rcDisplay_stopDeathMonitor_syncRcStack(); 3510 mRcDisplay = null; 3511 } 3512 } 3513 } 3514 3515 /** 3516 * Update the remote control clients with the new "focused" client generation 3517 */ 3518 private void setNewRcClientGenerationOnClients_syncRcsCurrc(int newClientGeneration) { 3519 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3520 while(stackIterator.hasNext()) { 3521 RemoteControlStackEntry se = stackIterator.next(); 3522 if ((se != null) && (se.mRcClient != null)) { 3523 try { 3524 se.mRcClient.setCurrentClientGenerationId(newClientGeneration); 3525 } catch (RemoteException e) { 3526 Log.w(TAG, "Dead client in setNewRcClientGenerationOnClients_syncRcsCurrc()"+e); 3527 stackIterator.remove(); 3528 se.unlinkToRcClientDeath(); 3529 } 3530 } 3531 } 3532 } 3533 3534 /** 3535 * Update the displays and clients with the new "focused" client generation and name 3536 * @param newClientGeneration the new generation value matching a client update 3537 * @param newClientEventReceiver the media button event receiver associated with the client. 3538 * May be null, which implies there is no registered media button event receiver. 3539 * @param clearing true if the new client generation value maps to a remote control update 3540 * where the display should be cleared. 3541 */ 3542 private void setNewRcClient_syncRcsCurrc(int newClientGeneration, 3543 PendingIntent newMediaIntent, boolean clearing) { 3544 // send the new valid client generation ID to all displays 3545 setNewRcClientOnDisplays_syncRcsCurrc(newClientGeneration, newMediaIntent, clearing); 3546 // send the new valid client generation ID to all clients 3547 setNewRcClientGenerationOnClients_syncRcsCurrc(newClientGeneration); 3548 } 3549 3550 /** 3551 * Called when processing MSG_RCDISPLAY_CLEAR event 3552 */ 3553 private void onRcDisplayClear() { 3554 if (DEBUG_RC) Log.i(TAG, "Clear remote control display"); 3555 3556 synchronized(mRCStack) { 3557 synchronized(mCurrentRcLock) { 3558 mCurrentRcClientGen++; 3559 // synchronously update the displays and clients with the new client generation 3560 setNewRcClient_syncRcsCurrc(mCurrentRcClientGen, 3561 null /*newMediaIntent*/, true /*clearing*/); 3562 } 3563 } 3564 } 3565 3566 /** 3567 * Called when processing MSG_RCDISPLAY_UPDATE event 3568 */ 3569 private void onRcDisplayUpdate(RemoteControlStackEntry rcse, int flags /* USED ?*/) { 3570 synchronized(mRCStack) { 3571 synchronized(mCurrentRcLock) { 3572 if ((mCurrentRcClient != null) && (mCurrentRcClient.equals(rcse.mRcClient))) { 3573 if (DEBUG_RC) Log.i(TAG, "Display/update remote control "); 3574 3575 mCurrentRcClientGen++; 3576 // synchronously update the displays and clients with 3577 // the new client generation 3578 setNewRcClient_syncRcsCurrc(mCurrentRcClientGen, 3579 rcse.mMediaIntent /*newMediaIntent*/, 3580 false /*clearing*/); 3581 3582 // tell the current client that it needs to send info 3583 try { 3584 mCurrentRcClient.onInformationRequested(mCurrentRcClientGen, 3585 flags, mArtworkExpectedWidth, mArtworkExpectedHeight); 3586 } catch (RemoteException e) { 3587 Log.e(TAG, "Current valid remote client is dead: "+e); 3588 mCurrentRcClient = null; 3589 } 3590 } else { 3591 // the remote control display owner has changed between the 3592 // the message to update the display was sent, and the time it 3593 // gets to be processed (now) 3594 } 3595 } 3596 } 3597 } 3598 3599 3600 /** 3601 * Helper function: 3602 * Called synchronized on mRCStack 3603 */ 3604 private void clearRemoteControlDisplay_syncAfRcs() { 3605 synchronized(mCurrentRcLock) { 3606 mCurrentRcClient = null; 3607 } 3608 // will cause onRcDisplayClear() to be called in AudioService's handler thread 3609 mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_CLEAR) ); 3610 } 3611 3612 /** 3613 * Helper function for code readability: only to be called from 3614 * checkUpdateRemoteControlDisplay_syncAfRcs() which checks the preconditions for 3615 * this method. 3616 * Preconditions: 3617 * - called synchronized mAudioFocusLock then on mRCStack 3618 * - mRCStack.isEmpty() is false 3619 */ 3620 private void updateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) { 3621 RemoteControlStackEntry rcse = mRCStack.peek(); 3622 int infoFlagsAboutToBeUsed = infoChangedFlags; 3623 // this is where we enforce opt-in for information display on the remote controls 3624 // with the new AudioManager.registerRemoteControlClient() API 3625 if (rcse.mRcClient == null) { 3626 //Log.w(TAG, "Can't update remote control display with null remote control client"); 3627 clearRemoteControlDisplay_syncAfRcs(); 3628 return; 3629 } 3630 synchronized(mCurrentRcLock) { 3631 if (!rcse.mRcClient.equals(mCurrentRcClient)) { 3632 // new RC client, assume every type of information shall be queried 3633 infoFlagsAboutToBeUsed = RC_INFO_ALL; 3634 } 3635 mCurrentRcClient = rcse.mRcClient; 3636 } 3637 // will cause onRcDisplayUpdate() to be called in AudioService's handler thread 3638 mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_UPDATE, 3639 infoFlagsAboutToBeUsed /* arg1 */, 0, rcse /* obj, != null */) ); 3640 } 3641 3642 /** 3643 * Helper function: 3644 * Called synchronized on mAudioFocusLock, then mRCStack 3645 * Check whether the remote control display should be updated, triggers the update if required 3646 * @param infoChangedFlags the flags corresponding to the remote control client information 3647 * that has changed, if applicable (checking for the update conditions might trigger a 3648 * clear, rather than an update event). 3649 */ 3650 private void checkUpdateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) { 3651 // determine whether the remote control display should be refreshed 3652 // if either stack is empty, there is a mismatch, so clear the RC display 3653 if (mRCStack.isEmpty() || mFocusStack.isEmpty()) { 3654 clearRemoteControlDisplay_syncAfRcs(); 3655 return; 3656 } 3657 // if the top of the two stacks belong to different packages, there is a mismatch, clear 3658 if ((mRCStack.peek().mCallingPackageName != null) 3659 && (mFocusStack.peek().mPackageName != null) 3660 && !(mRCStack.peek().mCallingPackageName.compareTo( 3661 mFocusStack.peek().mPackageName) == 0)) { 3662 clearRemoteControlDisplay_syncAfRcs(); 3663 return; 3664 } 3665 // if the audio focus didn't originate from the same Uid as the one in which the remote 3666 // control information will be retrieved, clear 3667 if (mRCStack.peek().mCallingUid != mFocusStack.peek().mCallingUid) { 3668 clearRemoteControlDisplay_syncAfRcs(); 3669 return; 3670 } 3671 // refresh conditions were verified: update the remote controls 3672 // ok to call: synchronized mAudioFocusLock then on mRCStack, mRCStack is not empty 3673 updateRemoteControlDisplay_syncAfRcs(infoChangedFlags); 3674 } 3675 3676 /** 3677 * see AudioManager.registerMediaButtonIntent(PendingIntent pi, ComponentName c) 3678 * precondition: mediaIntent != null, target != null 3679 */ 3680 public void registerMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver) { 3681 Log.i(TAG, " Remote Control registerMediaButtonIntent() for " + mediaIntent); 3682 3683 synchronized(mAudioFocusLock) { 3684 synchronized(mRCStack) { 3685 pushMediaButtonReceiver(mediaIntent, eventReceiver); 3686 // new RC client, assume every type of information shall be queried 3687 checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); 3688 } 3689 } 3690 } 3691 3692 /** 3693 * see AudioManager.unregisterMediaButtonIntent(PendingIntent mediaIntent) 3694 * precondition: mediaIntent != null, eventReceiver != null 3695 */ 3696 public void unregisterMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver) 3697 { 3698 Log.i(TAG, " Remote Control unregisterMediaButtonIntent() for " + mediaIntent); 3699 3700 synchronized(mAudioFocusLock) { 3701 synchronized(mRCStack) { 3702 boolean topOfStackWillChange = isCurrentRcController(mediaIntent); 3703 removeMediaButtonReceiver(mediaIntent); 3704 if (topOfStackWillChange) { 3705 // current RC client will change, assume every type of info needs to be queried 3706 checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); 3707 } 3708 } 3709 } 3710 } 3711 3712 /** 3713 * see AudioManager.registerRemoteControlClient(ComponentName eventReceiver, ...) 3714 * Note: using this method with rcClient == null is a way to "disable" the IRemoteControlClient 3715 * without modifying the RC stack, but while still causing the display to refresh (will 3716 * become blank as a result of this) 3717 */ 3718 public void registerRemoteControlClient(PendingIntent mediaIntent, 3719 IRemoteControlClient rcClient, String callingPackageName) { 3720 if (DEBUG_RC) Log.i(TAG, "Register remote control client rcClient="+rcClient); 3721 synchronized(mAudioFocusLock) { 3722 synchronized(mRCStack) { 3723 // store the new display information 3724 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3725 while(stackIterator.hasNext()) { 3726 RemoteControlStackEntry rcse = stackIterator.next(); 3727 if(rcse.mMediaIntent.equals(mediaIntent)) { 3728 // already had a remote control client? 3729 if (rcse.mRcClientDeathHandler != null) { 3730 // stop monitoring the old client's death 3731 rcse.unlinkToRcClientDeath(); 3732 } 3733 // save the new remote control client 3734 rcse.mRcClient = rcClient; 3735 rcse.mCallingPackageName = callingPackageName; 3736 rcse.mCallingUid = Binder.getCallingUid(); 3737 if (rcClient == null) { 3738 // here rcse.mRcClientDeathHandler is null; 3739 break; 3740 } 3741 3742 // there is a new (non-null) client: 3743 // 1/ give the new client the current display (if any) 3744 if (mRcDisplay != null) { 3745 try { 3746 rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay); 3747 } catch (RemoteException e) { 3748 Log.e(TAG, "Error connecting remote control display to client: "+e); 3749 e.printStackTrace(); 3750 } 3751 } 3752 // 2/ monitor the new client's death 3753 IBinder b = rcse.mRcClient.asBinder(); 3754 RcClientDeathHandler rcdh = 3755 new RcClientDeathHandler(b, rcse.mMediaIntent); 3756 try { 3757 b.linkToDeath(rcdh, 0); 3758 } catch (RemoteException e) { 3759 // remote control client is DOA, disqualify it 3760 Log.w(TAG, "registerRemoteControlClient() has a dead client " + b); 3761 rcse.mRcClient = null; 3762 } 3763 rcse.mRcClientDeathHandler = rcdh; 3764 break; 3765 } 3766 } 3767 // if the eventReceiver is at the top of the stack 3768 // then check for potential refresh of the remote controls 3769 if (isCurrentRcController(mediaIntent)) { 3770 checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); 3771 } 3772 } 3773 } 3774 } 3775 3776 /** 3777 * see AudioManager.unregisterRemoteControlClient(PendingIntent pi, ...) 3778 * rcClient is guaranteed non-null 3779 */ 3780 public void unregisterRemoteControlClient(PendingIntent mediaIntent, 3781 IRemoteControlClient rcClient) { 3782 synchronized(mAudioFocusLock) { 3783 synchronized(mRCStack) { 3784 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3785 while(stackIterator.hasNext()) { 3786 RemoteControlStackEntry rcse = stackIterator.next(); 3787 if ((rcse.mMediaIntent.equals(mediaIntent)) 3788 && rcClient.equals(rcse.mRcClient)) { 3789 // we found the IRemoteControlClient to unregister 3790 // stop monitoring its death 3791 rcse.unlinkToRcClientDeath(); 3792 // reset the client-related fields 3793 rcse.mRcClient = null; 3794 rcse.mCallingPackageName = null; 3795 } 3796 } 3797 } 3798 } 3799 } 3800 3801 /** 3802 * The remote control displays. 3803 * Access synchronized on mRCStack 3804 * NOTE: Only one IRemoteControlDisplay supported in this implementation 3805 */ 3806 private IRemoteControlDisplay mRcDisplay; 3807 private RcDisplayDeathHandler mRcDisplayDeathHandler; 3808 private int mArtworkExpectedWidth = -1; 3809 private int mArtworkExpectedHeight = -1; 3810 /** 3811 * Inner class to monitor remote control display deaths, and unregister them from the list 3812 * of displays if necessary. 3813 */ 3814 private class RcDisplayDeathHandler implements IBinder.DeathRecipient { 3815 private IBinder mCb; // To be notified of client's death 3816 3817 public RcDisplayDeathHandler(IBinder b) { 3818 if (DEBUG_RC) Log.i(TAG, "new RcDisplayDeathHandler for "+b); 3819 mCb = b; 3820 } 3821 3822 public void binderDied() { 3823 synchronized(mRCStack) { 3824 Log.w(TAG, "RemoteControl: display died"); 3825 mRcDisplay = null; 3826 } 3827 } 3828 3829 public void unlinkToRcDisplayDeath() { 3830 if (DEBUG_RC) Log.i(TAG, "unlinkToRcDisplayDeath for "+mCb); 3831 try { 3832 mCb.unlinkToDeath(this, 0); 3833 } catch (java.util.NoSuchElementException e) { 3834 // not much we can do here, the display was being unregistered anyway 3835 Log.e(TAG, "Encountered " + e + " in unlinkToRcDisplayDeath()"); 3836 e.printStackTrace(); 3837 } 3838 } 3839 3840 } 3841 3842 private void rcDisplay_stopDeathMonitor_syncRcStack() { 3843 if (mRcDisplay != null) { // implies (mRcDisplayDeathHandler != null) 3844 // we had a display before, stop monitoring its death 3845 mRcDisplayDeathHandler.unlinkToRcDisplayDeath(); 3846 } 3847 } 3848 3849 private void rcDisplay_startDeathMonitor_syncRcStack() { 3850 if (mRcDisplay != null) { 3851 // new non-null display, monitor its death 3852 IBinder b = mRcDisplay.asBinder(); 3853 mRcDisplayDeathHandler = new RcDisplayDeathHandler(b); 3854 try { 3855 b.linkToDeath(mRcDisplayDeathHandler, 0); 3856 } catch (RemoteException e) { 3857 // remote control display is DOA, disqualify it 3858 Log.w(TAG, "registerRemoteControlDisplay() has a dead client " + b); 3859 mRcDisplay = null; 3860 } 3861 } 3862 } 3863 3864 /** 3865 * Register an IRemoteControlDisplay. 3866 * Notify all IRemoteControlClient of the new display and cause the RemoteControlClient 3867 * at the top of the stack to update the new display with its information. 3868 * Since only one IRemoteControlDisplay is supported, this will unregister the previous display. 3869 * @param rcd the IRemoteControlDisplay to register. No effect if null. 3870 */ 3871 public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) { 3872 if (DEBUG_RC) Log.d(TAG, ">>> registerRemoteControlDisplay("+rcd+")"); 3873 synchronized(mAudioFocusLock) { 3874 synchronized(mRCStack) { 3875 if ((mRcDisplay == rcd) || (rcd == null)) { 3876 return; 3877 } 3878 // if we had a display before, stop monitoring its death 3879 rcDisplay_stopDeathMonitor_syncRcStack(); 3880 mRcDisplay = rcd; 3881 // new display, start monitoring its death 3882 rcDisplay_startDeathMonitor_syncRcStack(); 3883 3884 // let all the remote control clients there is a new display 3885 // no need to unplug the previous because we only support one display 3886 // and the clients don't track the death of the display 3887 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3888 while(stackIterator.hasNext()) { 3889 RemoteControlStackEntry rcse = stackIterator.next(); 3890 if(rcse.mRcClient != null) { 3891 try { 3892 rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay); 3893 } catch (RemoteException e) { 3894 Log.e(TAG, "Error connecting remote control display to client: " + e); 3895 e.printStackTrace(); 3896 } 3897 } 3898 } 3899 3900 // we have a new display, of which all the clients are now aware: have it be updated 3901 checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); 3902 } 3903 } 3904 } 3905 3906 /** 3907 * Unregister an IRemoteControlDisplay. 3908 * Since only one IRemoteControlDisplay is supported, this has no effect if the one to 3909 * unregister is not the current one. 3910 * @param rcd the IRemoteControlDisplay to unregister. No effect if null. 3911 */ 3912 public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) { 3913 if (DEBUG_RC) Log.d(TAG, "<<< unregisterRemoteControlDisplay("+rcd+")"); 3914 synchronized(mRCStack) { 3915 // only one display here, so you can only unregister the current display 3916 if ((rcd == null) || (rcd != mRcDisplay)) { 3917 if (DEBUG_RC) Log.w(TAG, " trying to unregister unregistered RCD"); 3918 return; 3919 } 3920 // if we had a display before, stop monitoring its death 3921 rcDisplay_stopDeathMonitor_syncRcStack(); 3922 mRcDisplay = null; 3923 3924 // disconnect this remote control display from all the clients 3925 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 3926 while(stackIterator.hasNext()) { 3927 RemoteControlStackEntry rcse = stackIterator.next(); 3928 if(rcse.mRcClient != null) { 3929 try { 3930 rcse.mRcClient.unplugRemoteControlDisplay(rcd); 3931 } catch (RemoteException e) { 3932 Log.e(TAG, "Error disconnecting remote control display to client: " + e); 3933 e.printStackTrace(); 3934 } 3935 } 3936 } 3937 } 3938 } 3939 3940 public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) { 3941 synchronized(mRCStack) { 3942 // NOTE: Only one IRemoteControlDisplay supported in this implementation 3943 mArtworkExpectedWidth = w; 3944 mArtworkExpectedHeight = h; 3945 } 3946 } 3947 3948 @Override 3949 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3950 // TODO probably a lot more to do here than just the audio focus and remote control stacks 3951 dumpFocusStack(pw); 3952 dumpRCStack(pw); 3953 } 3954 3955 3956} 3957