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