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