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