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