AudioService.java revision c03befe3d62eb2a3e1d56fec0ca188a6094d53dd
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 java.util.NoSuchElementException; 20import android.app.ActivityManagerNative; 21import android.content.BroadcastReceiver; 22import android.content.ComponentName; 23import android.content.ContentResolver; 24import android.content.Context; 25import android.content.Intent; 26import android.content.IntentFilter; 27import android.bluetooth.BluetoothA2dp; 28import android.bluetooth.BluetoothClass; 29import android.bluetooth.BluetoothDevice; 30import android.bluetooth.BluetoothHeadset; 31import android.content.pm.PackageManager; 32import android.database.ContentObserver; 33import android.media.MediaPlayer.OnCompletionListener; 34import android.media.MediaPlayer.OnErrorListener; 35import android.os.Binder; 36import android.os.Environment; 37import android.os.Handler; 38import android.os.IBinder; 39import android.os.Looper; 40import android.os.Message; 41import android.os.RemoteException; 42import android.os.ServiceManager; 43import android.provider.Settings; 44import android.provider.Settings.System; 45import android.telephony.PhoneStateListener; 46import android.telephony.TelephonyManager; 47import android.util.Log; 48import android.view.KeyEvent; 49import android.view.VolumePanel; 50import android.os.SystemProperties; 51 52import com.android.internal.telephony.ITelephony; 53 54import java.io.FileDescriptor; 55import java.io.IOException; 56import java.io.PrintWriter; 57import java.util.ArrayList; 58import java.util.HashMap; 59import java.util.Iterator; 60import java.util.Map; 61import java.util.Set; 62import java.util.Stack; 63 64/** 65 * The implementation of the volume manager service. 66 * <p> 67 * This implementation focuses on delivering a responsive UI. Most methods are 68 * asynchronous to external calls. For example, the task of setting a volume 69 * will update our internal state, but in a separate thread will set the system 70 * volume and later persist to the database. Similarly, setting the ringer mode 71 * will update the state and broadcast a change and in a separate thread later 72 * persist the ringer mode. 73 * 74 * @hide 75 */ 76public class AudioService extends IAudioService.Stub { 77 78 private static final String TAG = "AudioService"; 79 80 /** How long to delay before persisting a change in volume/ringer mode. */ 81 private static final int PERSIST_DELAY = 3000; 82 83 private Context mContext; 84 private ContentResolver mContentResolver; 85 86 87 /** The UI */ 88 private VolumePanel mVolumePanel; 89 90 // sendMsg() flags 91 /** Used when a message should be shared across all stream types. */ 92 private static final int SHARED_MSG = -1; 93 /** If the msg is already queued, replace it with this one. */ 94 private static final int SENDMSG_REPLACE = 0; 95 /** If the msg is already queued, ignore this one and leave the old. */ 96 private static final int SENDMSG_NOOP = 1; 97 /** If the msg is already queued, queue this one and leave the old. */ 98 private static final int SENDMSG_QUEUE = 2; 99 100 // AudioHandler message.whats 101 private static final int MSG_SET_SYSTEM_VOLUME = 0; 102 private static final int MSG_PERSIST_VOLUME = 1; 103 private static final int MSG_PERSIST_RINGER_MODE = 3; 104 private static final int MSG_PERSIST_VIBRATE_SETTING = 4; 105 private static final int MSG_MEDIA_SERVER_DIED = 5; 106 private static final int MSG_MEDIA_SERVER_STARTED = 6; 107 private static final int MSG_PLAY_SOUND_EFFECT = 7; 108 private static final int MSG_BTA2DP_DOCK_TIMEOUT = 8; 109 110 private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000; 111 112 /** @see AudioSystemThread */ 113 private AudioSystemThread mAudioSystemThread; 114 /** @see AudioHandler */ 115 private AudioHandler mAudioHandler; 116 /** @see VolumeStreamState */ 117 private VolumeStreamState[] mStreamStates; 118 private SettingsObserver mSettingsObserver; 119 120 private int mMode; 121 private Object mSettingsLock = new Object(); 122 private boolean mMediaServerOk; 123 124 private SoundPool mSoundPool; 125 private Object mSoundEffectsLock = new Object(); 126 private static final int NUM_SOUNDPOOL_CHANNELS = 4; 127 private static final int SOUND_EFFECT_VOLUME = 1000; 128 129 /* Sound effect file names */ 130 private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/"; 131 private static final String[] SOUND_EFFECT_FILES = new String[] { 132 "Effect_Tick.ogg", 133 "KeypressStandard.ogg", 134 "KeypressSpacebar.ogg", 135 "KeypressDelete.ogg", 136 "KeypressReturn.ogg" 137 }; 138 139 /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to 140 * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect 141 * uses soundpool (second column) */ 142 private int[][] SOUND_EFFECT_FILES_MAP = new int[][] { 143 {0, -1}, // FX_KEY_CLICK 144 {0, -1}, // FX_FOCUS_NAVIGATION_UP 145 {0, -1}, // FX_FOCUS_NAVIGATION_DOWN 146 {0, -1}, // FX_FOCUS_NAVIGATION_LEFT 147 {0, -1}, // FX_FOCUS_NAVIGATION_RIGHT 148 {1, -1}, // FX_KEYPRESS_STANDARD 149 {2, -1}, // FX_KEYPRESS_SPACEBAR 150 {3, -1}, // FX_FOCUS_DELETE 151 {4, -1} // FX_FOCUS_RETURN 152 }; 153 154 /** @hide Maximum volume index values for audio streams */ 155 private int[] MAX_STREAM_VOLUME = new int[] { 156 5, // STREAM_VOICE_CALL 157 7, // STREAM_SYSTEM 158 7, // STREAM_RING 159 15, // STREAM_MUSIC 160 7, // STREAM_ALARM 161 7, // STREAM_NOTIFICATION 162 15, // STREAM_BLUETOOTH_SCO 163 7, // STREAM_SYSTEM_ENFORCED 164 15, // STREAM_DTMF 165 15 // STREAM_TTS 166 }; 167 /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings 168 * of another stream: This avoids multiplying the volume settings for hidden 169 * stream types that follow other stream behavior for volume settings 170 * NOTE: do not create loops in aliases! */ 171 private int[] STREAM_VOLUME_ALIAS = new int[] { 172 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL 173 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM 174 AudioSystem.STREAM_RING, // STREAM_RING 175 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC 176 AudioSystem.STREAM_ALARM, // STREAM_ALARM 177 AudioSystem.STREAM_NOTIFICATION, // STREAM_NOTIFICATION 178 AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO 179 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM_ENFORCED 180 AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF 181 AudioSystem.STREAM_MUSIC // STREAM_TTS 182 }; 183 184 private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() { 185 public void onError(int error) { 186 switch (error) { 187 case AudioSystem.AUDIO_STATUS_SERVER_DIED: 188 if (mMediaServerOk) { 189 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0, 190 null, 1500); 191 mMediaServerOk = false; 192 } 193 break; 194 case AudioSystem.AUDIO_STATUS_OK: 195 if (!mMediaServerOk) { 196 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0, 197 null, 0); 198 mMediaServerOk = true; 199 } 200 break; 201 default: 202 break; 203 } 204 } 205 }; 206 207 /** 208 * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL}, 209 * {@link AudioManager#RINGER_MODE_SILENT}, or 210 * {@link AudioManager#RINGER_MODE_VIBRATE}. 211 */ 212 private int mRingerMode; 213 214 /** @see System#MODE_RINGER_STREAMS_AFFECTED */ 215 private int mRingerModeAffectedStreams; 216 217 // Streams currently muted by ringer mode 218 private int mRingerModeMutedStreams; 219 220 /** @see System#MUTE_STREAMS_AFFECTED */ 221 private int mMuteAffectedStreams; 222 223 /** 224 * Has multiple bits per vibrate type to indicate the type's vibrate 225 * setting. See {@link #setVibrateSetting(int, int)}. 226 * <p> 227 * NOTE: This is not the final decision of whether vibrate is on/off for the 228 * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}. 229 */ 230 private int mVibrateSetting; 231 232 /** @see System#NOTIFICATIONS_USE_RING_VOLUME */ 233 private int mNotificationsUseRingVolume; 234 235 // Broadcast receiver for device connections intent broadcasts 236 private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver(); 237 238 // Broadcast receiver for media button broadcasts (separate from mReceiver to 239 // independently change its priority) 240 private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver(); 241 242 // Devices currently connected 243 private HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>(); 244 245 // Forced device usage for communications 246 private int mForcedUseForComm; 247 248 // List of binder death handlers for setMode() client processes. 249 // The last process to have called setMode() is at the top of the list. 250 private ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>(); 251 252 // List of clients having issued a SCO start request 253 private ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>(); 254 255 // BluetoothHeadset API to control SCO connection 256 private BluetoothHeadset mBluetoothHeadset; 257 258 // Bluetooth headset connection state 259 private boolean mBluetoothHeadsetConnected; 260 261 /////////////////////////////////////////////////////////////////////////// 262 // Construction 263 /////////////////////////////////////////////////////////////////////////// 264 265 /** @hide */ 266 public AudioService(Context context) { 267 mContext = context; 268 mContentResolver = context.getContentResolver(); 269 270 // Intialized volume 271 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt( 272 "ro.config.vc_call_vol_steps", 273 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]); 274 275 mVolumePanel = new VolumePanel(context, this); 276 mSettingsObserver = new SettingsObserver(); 277 mForcedUseForComm = AudioSystem.FORCE_NONE; 278 createAudioSystemThread(); 279 readPersistedSettings(); 280 createStreamStates(); 281 // Call setMode() to initialize mSetModeDeathHandlers 282 mMode = AudioSystem.MODE_INVALID; 283 setMode(AudioSystem.MODE_NORMAL, null); 284 mMediaServerOk = true; 285 286 // Call setRingerModeInt() to apply correct mute 287 // state on streams affected by ringer mode. 288 mRingerModeMutedStreams = 0; 289 setRingerModeInt(getRingerMode(), false); 290 291 AudioSystem.setErrorCallback(mAudioSystemCallback); 292 loadSoundEffects(); 293 294 mBluetoothHeadsetConnected = false; 295 mBluetoothHeadset = new BluetoothHeadset(context, 296 mBluetoothHeadsetServiceListener); 297 298 // Register for device connection intent broadcasts. 299 IntentFilter intentFilter = 300 new IntentFilter(Intent.ACTION_HEADSET_PLUG); 301 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED); 302 intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED); 303 intentFilter.addAction(Intent.ACTION_DOCK_EVENT); 304 intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); 305 context.registerReceiver(mReceiver, intentFilter); 306 307 // Register for media button intent broadcasts. 308 intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON); 309 intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 310 context.registerReceiver(mMediaButtonReceiver, intentFilter); 311 312 // Register for phone state monitoring 313 TelephonyManager tmgr = (TelephonyManager) 314 context.getSystemService(Context.TELEPHONY_SERVICE); 315 tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 316 } 317 318 private void createAudioSystemThread() { 319 mAudioSystemThread = new AudioSystemThread(); 320 mAudioSystemThread.start(); 321 waitForAudioHandlerCreation(); 322 } 323 324 /** Waits for the volume handler to be created by the other thread. */ 325 private void waitForAudioHandlerCreation() { 326 synchronized(this) { 327 while (mAudioHandler == null) { 328 try { 329 // Wait for mAudioHandler to be set by the other thread 330 wait(); 331 } catch (InterruptedException e) { 332 Log.e(TAG, "Interrupted while waiting on volume handler."); 333 } 334 } 335 } 336 } 337 338 private void createStreamStates() { 339 int numStreamTypes = AudioSystem.getNumStreamTypes(); 340 VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes]; 341 342 for (int i = 0; i < numStreamTypes; i++) { 343 streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i); 344 } 345 346 // Correct stream index values for streams with aliases 347 for (int i = 0; i < numStreamTypes; i++) { 348 if (STREAM_VOLUME_ALIAS[i] != i) { 349 int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i); 350 streams[i].mIndex = streams[i].getValidIndex(index); 351 setStreamVolumeIndex(i, index); 352 index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i); 353 streams[i].mLastAudibleIndex = streams[i].getValidIndex(index); 354 } 355 } 356 } 357 358 private void readPersistedSettings() { 359 final ContentResolver cr = mContentResolver; 360 361 mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL); 362 363 mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0); 364 365 mRingerModeAffectedStreams = Settings.System.getInt(cr, 366 Settings.System.MODE_RINGER_STREAMS_AFFECTED, 367 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)| 368 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED))); 369 370 mMuteAffectedStreams = System.getInt(cr, 371 System.MUTE_STREAMS_AFFECTED, 372 ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM))); 373 374 mNotificationsUseRingVolume = System.getInt(cr, 375 Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1); 376 377 if (mNotificationsUseRingVolume == 1) { 378 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING; 379 } 380 // Each stream will read its own persisted settings 381 382 // Broadcast the sticky intent 383 broadcastRingerMode(); 384 385 // Broadcast vibrate settings 386 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); 387 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION); 388 } 389 390 private void setStreamVolumeIndex(int stream, int index) { 391 AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10); 392 } 393 394 private int rescaleIndex(int index, int srcStream, int dstStream) { 395 return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex(); 396 } 397 398 /////////////////////////////////////////////////////////////////////////// 399 // IPC methods 400 /////////////////////////////////////////////////////////////////////////// 401 402 /** @see AudioManager#adjustVolume(int, int) */ 403 public void adjustVolume(int direction, int flags) { 404 adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags); 405 } 406 407 /** @see AudioManager#adjustVolume(int, int, int) */ 408 public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) { 409 410 int streamType = getActiveStreamType(suggestedStreamType); 411 412 // Don't play sound on other streams 413 if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) { 414 flags &= ~AudioManager.FLAG_PLAY_SOUND; 415 } 416 417 adjustStreamVolume(streamType, direction, flags); 418 } 419 420 /** @see AudioManager#adjustStreamVolume(int, int, int) */ 421 public void adjustStreamVolume(int streamType, int direction, int flags) { 422 ensureValidDirection(direction); 423 ensureValidStreamType(streamType); 424 425 426 VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]]; 427 final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex; 428 boolean adjustVolume = true; 429 430 // If either the client forces allowing ringer modes for this adjustment, 431 // or the stream type is one that is affected by ringer modes 432 if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0 433 || streamType == AudioSystem.STREAM_RING) { 434 // Check if the ringer mode changes with this volume adjustment. If 435 // it does, it will handle adjusting the volume, so we won't below 436 adjustVolume = checkForRingerModeChange(oldIndex, direction); 437 } 438 439 // If stream is muted, adjust last audible index only 440 int index; 441 if (streamState.muteCount() != 0) { 442 if (adjustVolume) { 443 streamState.adjustLastAudibleIndex(direction); 444 // Post a persist volume msg 445 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType, 446 SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY); 447 } 448 index = streamState.mLastAudibleIndex; 449 } else { 450 if (adjustVolume && streamState.adjustIndex(direction)) { 451 // Post message to set system volume (it in turn will post a message 452 // to persist). Do not change volume if stream is muted. 453 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, STREAM_VOLUME_ALIAS[streamType], SENDMSG_NOOP, 0, 0, 454 streamState, 0); 455 } 456 index = streamState.mIndex; 457 } 458 // UI 459 mVolumePanel.postVolumeChanged(streamType, flags); 460 // Broadcast Intent 461 sendVolumeUpdate(streamType, oldIndex, index); 462 } 463 464 /** @see AudioManager#setStreamVolume(int, int, int) */ 465 public void setStreamVolume(int streamType, int index, int flags) { 466 ensureValidStreamType(streamType); 467 VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]]; 468 469 final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex; 470 471 index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]); 472 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true); 473 474 index = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex; 475 476 // UI, etc. 477 mVolumePanel.postVolumeChanged(streamType, flags); 478 // Broadcast Intent 479 sendVolumeUpdate(streamType, oldIndex, index); 480 } 481 482 private void sendVolumeUpdate(int streamType, int oldIndex, int index) { 483 oldIndex = (oldIndex + 5) / 10; 484 index = (index + 5) / 10; 485 486 Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION); 487 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType); 488 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index); 489 intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex); 490 491 mContext.sendBroadcast(intent); 492 } 493 494 /** 495 * Sets the stream state's index, and posts a message to set system volume. 496 * This will not call out to the UI. Assumes a valid stream type. 497 * 498 * @param streamType Type of the stream 499 * @param index Desired volume index of the stream 500 * @param force If true, set the volume even if the desired volume is same 501 * as the current volume. 502 * @param lastAudible If true, stores new index as last audible one 503 */ 504 private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) { 505 VolumeStreamState streamState = mStreamStates[streamType]; 506 507 // If stream is muted, set last audible index only 508 if (streamState.muteCount() != 0) { 509 // Do not allow last audible index to be 0 510 if (index != 0) { 511 streamState.setLastAudibleIndex(index); 512 // Post a persist volume msg 513 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType, 514 SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY); 515 } 516 } else { 517 if (streamState.setIndex(index, lastAudible) || force) { 518 // Post message to set system volume (it in turn will post a message 519 // to persist). 520 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0, 521 streamState, 0); 522 } 523 } 524 } 525 526 /** @see AudioManager#setStreamSolo(int, boolean) */ 527 public void setStreamSolo(int streamType, boolean state, IBinder cb) { 528 for (int stream = 0; stream < mStreamStates.length; stream++) { 529 if (!isStreamAffectedByMute(stream) || stream == streamType) continue; 530 // Bring back last audible volume 531 mStreamStates[stream].mute(cb, state); 532 } 533 } 534 535 /** @see AudioManager#setStreamMute(int, boolean) */ 536 public void setStreamMute(int streamType, boolean state, IBinder cb) { 537 if (isStreamAffectedByMute(streamType)) { 538 mStreamStates[streamType].mute(cb, state); 539 } 540 } 541 542 /** @see AudioManager#getStreamVolume(int) */ 543 public int getStreamVolume(int streamType) { 544 ensureValidStreamType(streamType); 545 return (mStreamStates[streamType].mIndex + 5) / 10; 546 } 547 548 /** @see AudioManager#getStreamMaxVolume(int) */ 549 public int getStreamMaxVolume(int streamType) { 550 ensureValidStreamType(streamType); 551 return (mStreamStates[streamType].getMaxIndex() + 5) / 10; 552 } 553 554 /** @see AudioManager#getRingerMode() */ 555 public int getRingerMode() { 556 return mRingerMode; 557 } 558 559 /** @see AudioManager#setRingerMode(int) */ 560 public void setRingerMode(int ringerMode) { 561 synchronized (mSettingsLock) { 562 if (ringerMode != mRingerMode) { 563 setRingerModeInt(ringerMode, true); 564 // Send sticky broadcast 565 broadcastRingerMode(); 566 } 567 } 568 } 569 570 private void setRingerModeInt(int ringerMode, boolean persist) { 571 mRingerMode = ringerMode; 572 573 // Mute stream if not previously muted by ringer mode and ringer mode 574 // is not RINGER_MODE_NORMAL and stream is affected by ringer mode. 575 // Unmute stream if previously muted by ringer mode and ringer mode 576 // is RINGER_MODE_NORMAL or stream is not affected by ringer mode. 577 int numStreamTypes = AudioSystem.getNumStreamTypes(); 578 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 579 if (isStreamMutedByRingerMode(streamType)) { 580 if (!isStreamAffectedByRingerMode(streamType) || 581 mRingerMode == AudioManager.RINGER_MODE_NORMAL) { 582 mStreamStates[streamType].mute(null, false); 583 mRingerModeMutedStreams &= ~(1 << streamType); 584 } 585 } else { 586 if (isStreamAffectedByRingerMode(streamType) && 587 mRingerMode != AudioManager.RINGER_MODE_NORMAL) { 588 mStreamStates[streamType].mute(null, true); 589 mRingerModeMutedStreams |= (1 << streamType); 590 } 591 } 592 } 593 594 // Post a persist ringer mode msg 595 if (persist) { 596 sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG, 597 SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY); 598 } 599 } 600 601 /** @see AudioManager#shouldVibrate(int) */ 602 public boolean shouldVibrate(int vibrateType) { 603 604 switch (getVibrateSetting(vibrateType)) { 605 606 case AudioManager.VIBRATE_SETTING_ON: 607 return mRingerMode != AudioManager.RINGER_MODE_SILENT; 608 609 case AudioManager.VIBRATE_SETTING_ONLY_SILENT: 610 return mRingerMode == AudioManager.RINGER_MODE_VIBRATE; 611 612 case AudioManager.VIBRATE_SETTING_OFF: 613 // return false, even for incoming calls 614 return false; 615 616 default: 617 return false; 618 } 619 } 620 621 /** @see AudioManager#getVibrateSetting(int) */ 622 public int getVibrateSetting(int vibrateType) { 623 return (mVibrateSetting >> (vibrateType * 2)) & 3; 624 } 625 626 /** @see AudioManager#setVibrateSetting(int, int) */ 627 public void setVibrateSetting(int vibrateType, int vibrateSetting) { 628 629 mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting); 630 631 // Broadcast change 632 broadcastVibrateSetting(vibrateType); 633 634 // Post message to set ringer mode (it in turn will post a message 635 // to persist) 636 sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0, 637 null, 0); 638 } 639 640 /** 641 * @see #setVibrateSetting(int, int) 642 */ 643 public static int getValueForVibrateSetting(int existingValue, int vibrateType, 644 int vibrateSetting) { 645 646 // First clear the existing setting. Each vibrate type has two bits in 647 // the value. Note '3' is '11' in binary. 648 existingValue &= ~(3 << (vibrateType * 2)); 649 650 // Set into the old value 651 existingValue |= (vibrateSetting & 3) << (vibrateType * 2); 652 653 return existingValue; 654 } 655 656 private class SetModeDeathHandler implements IBinder.DeathRecipient { 657 private IBinder mCb; // To be notified of client's death 658 private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client 659 660 SetModeDeathHandler(IBinder cb) { 661 mCb = cb; 662 } 663 664 public void binderDied() { 665 synchronized(mSetModeDeathHandlers) { 666 Log.w(TAG, "setMode() client died"); 667 int index = mSetModeDeathHandlers.indexOf(this); 668 if (index < 0) { 669 Log.w(TAG, "unregistered setMode() client died"); 670 } else { 671 mSetModeDeathHandlers.remove(this); 672 // If dead client was a the top of client list, 673 // apply next mode in the stack 674 if (index == 0) { 675 // mSetModeDeathHandlers is never empty as the initial entry 676 // created when AudioService starts is never removed 677 SetModeDeathHandler hdlr = mSetModeDeathHandlers.get(0); 678 int mode = hdlr.getMode(); 679 if (AudioService.this.mMode != mode) { 680 if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) { 681 AudioService.this.mMode = mode; 682 } 683 } 684 } 685 } 686 } 687 } 688 689 public void setMode(int mode) { 690 mMode = mode; 691 } 692 693 public int getMode() { 694 return mMode; 695 } 696 697 public IBinder getBinder() { 698 return mCb; 699 } 700 } 701 702 /** @see AudioManager#setMode(int) */ 703 public void setMode(int mode, IBinder cb) { 704 if (!checkAudioSettingsPermission("setMode()")) { 705 return; 706 } 707 708 if (mode < AudioSystem.MODE_CURRENT || mode > AudioSystem.MODE_IN_CALL) { 709 return; 710 } 711 712 synchronized (mSettingsLock) { 713 if (mode == AudioSystem.MODE_CURRENT) { 714 mode = mMode; 715 } 716 if (mode != mMode) { 717 if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) { 718 mMode = mode; 719 720 synchronized(mSetModeDeathHandlers) { 721 SetModeDeathHandler hdlr = null; 722 Iterator iter = mSetModeDeathHandlers.iterator(); 723 while (iter.hasNext()) { 724 SetModeDeathHandler h = (SetModeDeathHandler)iter.next(); 725 if (h.getBinder() == cb) { 726 hdlr = h; 727 // Remove from client list so that it is re-inserted at top of list 728 iter.remove(); 729 break; 730 } 731 } 732 if (hdlr == null) { 733 hdlr = new SetModeDeathHandler(cb); 734 // cb is null when setMode() is called by AudioService constructor 735 if (cb != null) { 736 // Register for client death notification 737 try { 738 cb.linkToDeath(hdlr, 0); 739 } catch (RemoteException e) { 740 // Client has died! 741 Log.w(TAG, "setMode() could not link to "+cb+" binder death"); 742 } 743 } 744 } 745 // Last client to call setMode() is always at top of client list 746 // as required by SetModeDeathHandler.binderDied() 747 mSetModeDeathHandlers.add(0, hdlr); 748 hdlr.setMode(mode); 749 } 750 751 if (mode != AudioSystem.MODE_NORMAL) { 752 clearAllScoClients(); 753 } 754 } 755 } 756 int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); 757 int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex; 758 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, false); 759 } 760 } 761 762 /** @see AudioManager#getMode() */ 763 public int getMode() { 764 return mMode; 765 } 766 767 /** @see AudioManager#playSoundEffect(int) */ 768 public void playSoundEffect(int effectType) { 769 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, 770 effectType, -1, null, 0); 771 } 772 773 /** @see AudioManager#playSoundEffect(int, float) */ 774 public void playSoundEffectVolume(int effectType, float volume) { 775 loadSoundEffects(); 776 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, 777 effectType, (int) (volume * 1000), null, 0); 778 } 779 780 /** 781 * Loads samples into the soundpool. 782 * This method must be called at when sound effects are enabled 783 */ 784 public boolean loadSoundEffects() { 785 synchronized (mSoundEffectsLock) { 786 if (mSoundPool != null) { 787 return true; 788 } 789 mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0); 790 if (mSoundPool == null) { 791 return false; 792 } 793 /* 794 * poolId table: The value -1 in this table indicates that corresponding 795 * file (same index in SOUND_EFFECT_FILES[] has not been loaded. 796 * Once loaded, the value in poolId is the sample ID and the same 797 * sample can be reused for another effect using the same file. 798 */ 799 int[] poolId = new int[SOUND_EFFECT_FILES.length]; 800 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { 801 poolId[fileIdx] = -1; 802 } 803 /* 804 * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded. 805 * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0: 806 * this indicates we have a valid sample loaded for this effect. 807 */ 808 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { 809 // Do not load sample if this effect uses the MediaPlayer 810 if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) { 811 continue; 812 } 813 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) { 814 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]]; 815 int sampleId = mSoundPool.load(filePath, 0); 816 SOUND_EFFECT_FILES_MAP[effect][1] = sampleId; 817 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId; 818 if (sampleId <= 0) { 819 Log.w(TAG, "Soundpool could not load file: "+filePath); 820 } 821 } else { 822 SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]]; 823 } 824 } 825 } 826 827 return true; 828 } 829 830 /** 831 * Unloads samples from the sound pool. 832 * This method can be called to free some memory when 833 * sound effects are disabled. 834 */ 835 public void unloadSoundEffects() { 836 synchronized (mSoundEffectsLock) { 837 if (mSoundPool == null) { 838 return; 839 } 840 int[] poolId = new int[SOUND_EFFECT_FILES.length]; 841 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { 842 poolId[fileIdx] = 0; 843 } 844 845 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { 846 if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) { 847 continue; 848 } 849 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) { 850 mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]); 851 SOUND_EFFECT_FILES_MAP[effect][1] = -1; 852 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1; 853 } 854 } 855 mSoundPool = null; 856 } 857 } 858 859 /** @see AudioManager#reloadAudioSettings() */ 860 public void reloadAudioSettings() { 861 // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings 862 readPersistedSettings(); 863 864 // restore volume settings 865 int numStreamTypes = AudioSystem.getNumStreamTypes(); 866 for (int streamType = 0; streamType < numStreamTypes; streamType++) { 867 VolumeStreamState streamState = mStreamStates[streamType]; 868 869 String settingName = System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[streamType]]; 870 String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; 871 int index = Settings.System.getInt(mContentResolver, 872 settingName, 873 AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 874 if (STREAM_VOLUME_ALIAS[streamType] != streamType) { 875 index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType); 876 } else { 877 index *= 10; 878 } 879 streamState.mIndex = streamState.getValidIndex(index); 880 881 index = (index + 5) / 10; 882 index = Settings.System.getInt(mContentResolver, 883 lastAudibleSettingName, 884 (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 885 if (STREAM_VOLUME_ALIAS[streamType] != streamType) { 886 index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType); 887 } else { 888 index *= 10; 889 } 890 streamState.mLastAudibleIndex = streamState.getValidIndex(index); 891 892 // unmute stream that was muted but is not affect by mute anymore 893 if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) { 894 int size = streamState.mDeathHandlers.size(); 895 for (int i = 0; i < size; i++) { 896 streamState.mDeathHandlers.get(i).mMuteCount = 1; 897 streamState.mDeathHandlers.get(i).mute(false); 898 } 899 } 900 // apply stream volume 901 if (streamState.muteCount() == 0) { 902 setStreamVolumeIndex(streamType, streamState.mIndex); 903 } 904 } 905 906 // apply new ringer mode 907 setRingerModeInt(getRingerMode(), false); 908 } 909 910 /** @see AudioManager#setSpeakerphoneOn() */ 911 public void setSpeakerphoneOn(boolean on){ 912 if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) { 913 return; 914 } 915 if (on) { 916 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_SPEAKER); 917 mForcedUseForComm = AudioSystem.FORCE_SPEAKER; 918 } else { 919 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE); 920 mForcedUseForComm = AudioSystem.FORCE_NONE; 921 } 922 } 923 924 /** @see AudioManager#isSpeakerphoneOn() */ 925 public boolean isSpeakerphoneOn() { 926 if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER) { 927 return true; 928 } else { 929 return false; 930 } 931 } 932 933 /** @see AudioManager#setBluetoothScoOn() */ 934 public void setBluetoothScoOn(boolean on){ 935 if (!checkAudioSettingsPermission("setBluetoothScoOn()")) { 936 return; 937 } 938 if (on) { 939 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_BT_SCO); 940 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_BT_SCO); 941 mForcedUseForComm = AudioSystem.FORCE_BT_SCO; 942 } else { 943 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE); 944 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE); 945 mForcedUseForComm = AudioSystem.FORCE_NONE; 946 } 947 } 948 949 /** @see AudioManager#isBluetoothScoOn() */ 950 public boolean isBluetoothScoOn() { 951 if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) { 952 return true; 953 } else { 954 return false; 955 } 956 } 957 958 /** @see AudioManager#startBluetoothSco() */ 959 public void startBluetoothSco(IBinder cb){ 960 if (!checkAudioSettingsPermission("startBluetoothSco()")) { 961 return; 962 } 963 ScoClient client = getScoClient(cb); 964 client.incCount(); 965 } 966 967 /** @see AudioManager#stopBluetoothSco() */ 968 public void stopBluetoothSco(IBinder cb){ 969 if (!checkAudioSettingsPermission("stopBluetoothSco()")) { 970 return; 971 } 972 ScoClient client = getScoClient(cb); 973 client.decCount(); 974 } 975 976 private class ScoClient implements IBinder.DeathRecipient { 977 private IBinder mCb; // To be notified of client's death 978 private int mStartcount; // number of SCO connections started by this client 979 980 ScoClient(IBinder cb) { 981 mCb = cb; 982 mStartcount = 0; 983 } 984 985 public void binderDied() { 986 synchronized(mScoClients) { 987 Log.w(TAG, "SCO client died"); 988 int index = mScoClients.indexOf(this); 989 if (index < 0) { 990 Log.w(TAG, "unregistered SCO client died"); 991 } else { 992 clearCount(true); 993 mScoClients.remove(this); 994 } 995 } 996 } 997 998 public void incCount() { 999 synchronized(mScoClients) { 1000 requestScoState(BluetoothHeadset.AUDIO_STATE_CONNECTED); 1001 if (mStartcount == 0) { 1002 try { 1003 mCb.linkToDeath(this, 0); 1004 } catch (RemoteException e) { 1005 // client has already died! 1006 Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death"); 1007 } 1008 } 1009 mStartcount++; 1010 } 1011 } 1012 1013 public void decCount() { 1014 synchronized(mScoClients) { 1015 if (mStartcount == 0) { 1016 Log.w(TAG, "ScoClient.decCount() already 0"); 1017 } else { 1018 mStartcount--; 1019 if (mStartcount == 0) { 1020 try { 1021 mCb.unlinkToDeath(this, 0); 1022 } catch (NoSuchElementException e) { 1023 Log.w(TAG, "decCount() going to 0 but not registered to binder"); 1024 } 1025 } 1026 requestScoState(BluetoothHeadset.AUDIO_STATE_DISCONNECTED); 1027 } 1028 } 1029 } 1030 1031 public void clearCount(boolean stopSco) { 1032 synchronized(mScoClients) { 1033 if (mStartcount != 0) { 1034 try { 1035 mCb.unlinkToDeath(this, 0); 1036 } catch (NoSuchElementException e) { 1037 Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder"); 1038 } 1039 } 1040 mStartcount = 0; 1041 if (stopSco) { 1042 requestScoState(BluetoothHeadset.AUDIO_STATE_DISCONNECTED); 1043 } 1044 } 1045 } 1046 1047 public int getCount() { 1048 return mStartcount; 1049 } 1050 1051 public IBinder getBinder() { 1052 return mCb; 1053 } 1054 1055 public int totalCount() { 1056 synchronized(mScoClients) { 1057 int count = 0; 1058 int size = mScoClients.size(); 1059 for (int i = 0; i < size; i++) { 1060 count += mScoClients.get(i).getCount(); 1061 } 1062 return count; 1063 } 1064 } 1065 1066 private void requestScoState(int state) { 1067 if (totalCount() == 0 && 1068 mBluetoothHeadsetConnected && 1069 AudioService.this.mMode == AudioSystem.MODE_NORMAL) { 1070 if (state == BluetoothHeadset.AUDIO_STATE_CONNECTED) { 1071 mBluetoothHeadset.startVoiceRecognition(); 1072 } else { 1073 mBluetoothHeadset.stopVoiceRecognition(); 1074 } 1075 } 1076 } 1077 } 1078 1079 public ScoClient getScoClient(IBinder cb) { 1080 synchronized(mScoClients) { 1081 ScoClient client; 1082 int size = mScoClients.size(); 1083 for (int i = 0; i < size; i++) { 1084 client = mScoClients.get(i); 1085 if (client.getBinder() == cb) 1086 return client; 1087 } 1088 client = new ScoClient(cb); 1089 mScoClients.add(client); 1090 return client; 1091 } 1092 } 1093 1094 public void clearAllScoClients() { 1095 synchronized(mScoClients) { 1096 int size = mScoClients.size(); 1097 for (int i = 0; i < size; i++) { 1098 mScoClients.get(i).clearCount(false); 1099 } 1100 } 1101 } 1102 1103 private BluetoothHeadset.ServiceListener mBluetoothHeadsetServiceListener = 1104 new BluetoothHeadset.ServiceListener() { 1105 public void onServiceConnected() { 1106 if (mBluetoothHeadset != null && 1107 mBluetoothHeadset.getState() == BluetoothHeadset.STATE_CONNECTED) { 1108 mBluetoothHeadsetConnected = true; 1109 } 1110 } 1111 public void onServiceDisconnected() { 1112 if (mBluetoothHeadset != null && 1113 mBluetoothHeadset.getState() == BluetoothHeadset.STATE_DISCONNECTED) { 1114 mBluetoothHeadsetConnected = false; 1115 clearAllScoClients(); 1116 } 1117 } 1118 }; 1119 1120 /////////////////////////////////////////////////////////////////////////// 1121 // Internal methods 1122 /////////////////////////////////////////////////////////////////////////// 1123 1124 /** 1125 * Checks if the adjustment should change ringer mode instead of just 1126 * adjusting volume. If so, this will set the proper ringer mode and volume 1127 * indices on the stream states. 1128 */ 1129 private boolean checkForRingerModeChange(int oldIndex, int direction) { 1130 boolean adjustVolumeIndex = true; 1131 int newRingerMode = mRingerMode; 1132 1133 if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) { 1134 // audible mode, at the bottom of the scale 1135 if (direction == AudioManager.ADJUST_LOWER 1136 && (oldIndex + 5) / 10 == 1) { 1137 // "silent mode", but which one? 1138 newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1 1139 ? AudioManager.RINGER_MODE_VIBRATE 1140 : AudioManager.RINGER_MODE_SILENT; 1141 } 1142 } else { 1143 if (direction == AudioManager.ADJUST_RAISE) { 1144 // exiting silent mode 1145 newRingerMode = AudioManager.RINGER_MODE_NORMAL; 1146 } else { 1147 // prevent last audible index to reach 0 1148 adjustVolumeIndex = false; 1149 } 1150 } 1151 1152 if (newRingerMode != mRingerMode) { 1153 setRingerMode(newRingerMode); 1154 1155 /* 1156 * If we are changing ringer modes, do not increment/decrement the 1157 * volume index. Instead, the handler for the message above will 1158 * take care of changing the index. 1159 */ 1160 adjustVolumeIndex = false; 1161 } 1162 1163 return adjustVolumeIndex; 1164 } 1165 1166 public boolean isStreamAffectedByRingerMode(int streamType) { 1167 return (mRingerModeAffectedStreams & (1 << streamType)) != 0; 1168 } 1169 1170 private boolean isStreamMutedByRingerMode(int streamType) { 1171 return (mRingerModeMutedStreams & (1 << streamType)) != 0; 1172 } 1173 1174 public boolean isStreamAffectedByMute(int streamType) { 1175 return (mMuteAffectedStreams & (1 << streamType)) != 0; 1176 } 1177 1178 private void ensureValidDirection(int direction) { 1179 if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) { 1180 throw new IllegalArgumentException("Bad direction " + direction); 1181 } 1182 } 1183 1184 private void ensureValidStreamType(int streamType) { 1185 if (streamType < 0 || streamType >= mStreamStates.length) { 1186 throw new IllegalArgumentException("Bad stream type " + streamType); 1187 } 1188 } 1189 1190 private int getActiveStreamType(int suggestedStreamType) { 1191 boolean isOffhook = false; 1192 try { 1193 ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); 1194 if (phone != null) isOffhook = phone.isOffhook(); 1195 } catch (RemoteException e) { 1196 Log.w(TAG, "Couldn't connect to phone service", e); 1197 } 1198 1199 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) { 1200 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO..."); 1201 return AudioSystem.STREAM_BLUETOOTH_SCO; 1202 } else if (isOffhook || AudioSystem.isStreamActive(AudioSystem.STREAM_VOICE_CALL)) { 1203 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL..."); 1204 return AudioSystem.STREAM_VOICE_CALL; 1205 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC)) { 1206 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC..."); 1207 return AudioSystem.STREAM_MUSIC; 1208 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) { 1209 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING..."); 1210 return AudioSystem.STREAM_RING; 1211 } else { 1212 // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType); 1213 return suggestedStreamType; 1214 } 1215 } 1216 1217 private void broadcastRingerMode() { 1218 // Send sticky broadcast 1219 Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION); 1220 broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode); 1221 broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT 1222 | Intent.FLAG_RECEIVER_REPLACE_PENDING); 1223 long origCallerIdentityToken = Binder.clearCallingIdentity(); 1224 mContext.sendStickyBroadcast(broadcast); 1225 Binder.restoreCallingIdentity(origCallerIdentityToken); 1226 } 1227 1228 private void broadcastVibrateSetting(int vibrateType) { 1229 // Send broadcast 1230 if (ActivityManagerNative.isSystemReady()) { 1231 Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION); 1232 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType); 1233 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType)); 1234 mContext.sendBroadcast(broadcast); 1235 } 1236 } 1237 1238 // Message helper methods 1239 private static int getMsg(int baseMsg, int streamType) { 1240 return (baseMsg & 0xffff) | streamType << 16; 1241 } 1242 1243 private static int getMsgBase(int msg) { 1244 return msg & 0xffff; 1245 } 1246 1247 private static void sendMsg(Handler handler, int baseMsg, int streamType, 1248 int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) { 1249 int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType); 1250 1251 if (existingMsgPolicy == SENDMSG_REPLACE) { 1252 handler.removeMessages(msg); 1253 } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { 1254 return; 1255 } 1256 1257 handler 1258 .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay); 1259 } 1260 1261 boolean checkAudioSettingsPermission(String method) { 1262 if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS") 1263 == PackageManager.PERMISSION_GRANTED) { 1264 return true; 1265 } 1266 String msg = "Audio Settings Permission Denial: " + method + " from pid=" 1267 + Binder.getCallingPid() 1268 + ", uid=" + Binder.getCallingUid(); 1269 Log.w(TAG, msg); 1270 return false; 1271 } 1272 1273 1274 /////////////////////////////////////////////////////////////////////////// 1275 // Inner classes 1276 /////////////////////////////////////////////////////////////////////////// 1277 1278 public class VolumeStreamState { 1279 private final int mStreamType; 1280 1281 private String mVolumeIndexSettingName; 1282 private String mLastAudibleVolumeIndexSettingName; 1283 private int mIndexMax; 1284 private int mIndex; 1285 private int mLastAudibleIndex; 1286 private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death 1287 1288 private VolumeStreamState(String settingName, int streamType) { 1289 1290 setVolumeIndexSettingName(settingName); 1291 1292 mStreamType = streamType; 1293 1294 final ContentResolver cr = mContentResolver; 1295 mIndexMax = MAX_STREAM_VOLUME[streamType]; 1296 mIndex = Settings.System.getInt(cr, 1297 mVolumeIndexSettingName, 1298 AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 1299 mLastAudibleIndex = Settings.System.getInt(cr, 1300 mLastAudibleVolumeIndexSettingName, 1301 (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 1302 AudioSystem.initStreamVolume(streamType, 0, mIndexMax); 1303 mIndexMax *= 10; 1304 mIndex = getValidIndex(10 * mIndex); 1305 mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex); 1306 setStreamVolumeIndex(streamType, mIndex); 1307 mDeathHandlers = new ArrayList<VolumeDeathHandler>(); 1308 } 1309 1310 public void setVolumeIndexSettingName(String settingName) { 1311 mVolumeIndexSettingName = settingName; 1312 mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; 1313 } 1314 1315 public boolean adjustIndex(int deltaIndex) { 1316 return setIndex(mIndex + deltaIndex * 10, true); 1317 } 1318 1319 public boolean setIndex(int index, boolean lastAudible) { 1320 int oldIndex = mIndex; 1321 mIndex = getValidIndex(index); 1322 1323 if (oldIndex != mIndex) { 1324 if (lastAudible) { 1325 mLastAudibleIndex = mIndex; 1326 } 1327 // Apply change to all streams using this one as alias 1328 int numStreamTypes = AudioSystem.getNumStreamTypes(); 1329 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 1330 if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) { 1331 mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible); 1332 } 1333 } 1334 return true; 1335 } else { 1336 return false; 1337 } 1338 } 1339 1340 public void setLastAudibleIndex(int index) { 1341 mLastAudibleIndex = getValidIndex(index); 1342 } 1343 1344 public void adjustLastAudibleIndex(int deltaIndex) { 1345 setLastAudibleIndex(mLastAudibleIndex + deltaIndex * 10); 1346 } 1347 1348 public int getMaxIndex() { 1349 return mIndexMax; 1350 } 1351 1352 public void mute(IBinder cb, boolean state) { 1353 VolumeDeathHandler handler = getDeathHandler(cb, state); 1354 if (handler == null) { 1355 Log.e(TAG, "Could not get client death handler for stream: "+mStreamType); 1356 return; 1357 } 1358 handler.mute(state); 1359 } 1360 1361 private int getValidIndex(int index) { 1362 if (index < 0) { 1363 return 0; 1364 } else if (index > mIndexMax) { 1365 return mIndexMax; 1366 } 1367 1368 return index; 1369 } 1370 1371 private class VolumeDeathHandler implements IBinder.DeathRecipient { 1372 private IBinder mICallback; // To be notified of client's death 1373 private int mMuteCount; // Number of active mutes for this client 1374 1375 VolumeDeathHandler(IBinder cb) { 1376 mICallback = cb; 1377 } 1378 1379 public void mute(boolean state) { 1380 synchronized(mDeathHandlers) { 1381 if (state) { 1382 if (mMuteCount == 0) { 1383 // Register for client death notification 1384 try { 1385 // mICallback can be 0 if muted by AudioService 1386 if (mICallback != null) { 1387 mICallback.linkToDeath(this, 0); 1388 } 1389 mDeathHandlers.add(this); 1390 // If the stream is not yet muted by any client, set lvel to 0 1391 if (muteCount() == 0) { 1392 setIndex(0, false); 1393 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0, 1394 VolumeStreamState.this, 0); 1395 } 1396 } catch (RemoteException e) { 1397 // Client has died! 1398 binderDied(); 1399 mDeathHandlers.notify(); 1400 return; 1401 } 1402 } else { 1403 Log.w(TAG, "stream: "+mStreamType+" was already muted by this client"); 1404 } 1405 mMuteCount++; 1406 } else { 1407 if (mMuteCount == 0) { 1408 Log.e(TAG, "unexpected unmute for stream: "+mStreamType); 1409 } else { 1410 mMuteCount--; 1411 if (mMuteCount == 0) { 1412 // Unregistr from client death notification 1413 mDeathHandlers.remove(this); 1414 // mICallback can be 0 if muted by AudioService 1415 if (mICallback != null) { 1416 mICallback.unlinkToDeath(this, 0); 1417 } 1418 if (muteCount() == 0) { 1419 // If the stream is not muted any more, restore it's volume if 1420 // ringer mode allows it 1421 if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) { 1422 setIndex(mLastAudibleIndex, false); 1423 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0, 1424 VolumeStreamState.this, 0); 1425 } 1426 } 1427 } 1428 } 1429 } 1430 mDeathHandlers.notify(); 1431 } 1432 } 1433 1434 public void binderDied() { 1435 Log.w(TAG, "Volume service client died for stream: "+mStreamType); 1436 if (mMuteCount != 0) { 1437 // Reset all active mute requests from this client. 1438 mMuteCount = 1; 1439 mute(false); 1440 } 1441 } 1442 } 1443 1444 private int muteCount() { 1445 int count = 0; 1446 int size = mDeathHandlers.size(); 1447 for (int i = 0; i < size; i++) { 1448 count += mDeathHandlers.get(i).mMuteCount; 1449 } 1450 return count; 1451 } 1452 1453 private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) { 1454 synchronized(mDeathHandlers) { 1455 VolumeDeathHandler handler; 1456 int size = mDeathHandlers.size(); 1457 for (int i = 0; i < size; i++) { 1458 handler = mDeathHandlers.get(i); 1459 if (cb == handler.mICallback) { 1460 return handler; 1461 } 1462 } 1463 // If this is the first mute request for this client, create a new 1464 // client death handler. Otherwise, it is an out of sequence unmute request. 1465 if (state) { 1466 handler = new VolumeDeathHandler(cb); 1467 } else { 1468 Log.w(TAG, "stream was not muted by this client"); 1469 handler = null; 1470 } 1471 return handler; 1472 } 1473 } 1474 } 1475 1476 /** Thread that handles native AudioSystem control. */ 1477 private class AudioSystemThread extends Thread { 1478 AudioSystemThread() { 1479 super("AudioService"); 1480 } 1481 1482 @Override 1483 public void run() { 1484 // Set this thread up so the handler will work on it 1485 Looper.prepare(); 1486 1487 synchronized(AudioService.this) { 1488 mAudioHandler = new AudioHandler(); 1489 1490 // Notify that the handler has been created 1491 AudioService.this.notify(); 1492 } 1493 1494 // Listen for volume change requests that are set by VolumePanel 1495 Looper.loop(); 1496 } 1497 } 1498 1499 /** Handles internal volume messages in separate volume thread. */ 1500 private class AudioHandler extends Handler { 1501 1502 private void setSystemVolume(VolumeStreamState streamState) { 1503 1504 // Adjust volume 1505 setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex); 1506 1507 // Apply change to all streams using this one as alias 1508 int numStreamTypes = AudioSystem.getNumStreamTypes(); 1509 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 1510 if (streamType != streamState.mStreamType && 1511 STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) { 1512 setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex); 1513 } 1514 } 1515 1516 // Post a persist volume msg 1517 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType, 1518 SENDMSG_REPLACE, 1, 1, streamState, PERSIST_DELAY); 1519 } 1520 1521 private void persistVolume(VolumeStreamState streamState, boolean current, boolean lastAudible) { 1522 if (current) { 1523 System.putInt(mContentResolver, streamState.mVolumeIndexSettingName, 1524 (streamState.mIndex + 5)/ 10); 1525 } 1526 if (lastAudible) { 1527 System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName, 1528 (streamState.mLastAudibleIndex + 5) / 10); 1529 } 1530 } 1531 1532 private void persistRingerMode() { 1533 System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode); 1534 } 1535 1536 private void persistVibrateSetting() { 1537 System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting); 1538 } 1539 1540 private void playSoundEffect(int effectType, int volume) { 1541 synchronized (mSoundEffectsLock) { 1542 if (mSoundPool == null) { 1543 return; 1544 } 1545 float volFloat; 1546 // use STREAM_MUSIC volume attenuated by 3 dB if volume is not specified by caller 1547 if (volume < 0) { 1548 // Same linear to log conversion as in native AudioSystem::linearToLog() (AudioSystem.cpp) 1549 float dBPerStep = (float)((0.5 * 100) / MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]); 1550 int musicVolIndex = (mStreamStates[AudioSystem.STREAM_MUSIC].mIndex + 5) / 10; 1551 float musicVoldB = dBPerStep * (musicVolIndex - MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]); 1552 volFloat = (float)Math.pow(10, (musicVoldB - 3)/20); 1553 } else { 1554 volFloat = (float) volume / 1000.0f; 1555 } 1556 1557 if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) { 1558 mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f); 1559 } else { 1560 MediaPlayer mediaPlayer = new MediaPlayer(); 1561 if (mediaPlayer != null) { 1562 try { 1563 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]]; 1564 mediaPlayer.setDataSource(filePath); 1565 mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM); 1566 mediaPlayer.prepare(); 1567 mediaPlayer.setVolume(volFloat, volFloat); 1568 mediaPlayer.setOnCompletionListener(new OnCompletionListener() { 1569 public void onCompletion(MediaPlayer mp) { 1570 cleanupPlayer(mp); 1571 } 1572 }); 1573 mediaPlayer.setOnErrorListener(new OnErrorListener() { 1574 public boolean onError(MediaPlayer mp, int what, int extra) { 1575 cleanupPlayer(mp); 1576 return true; 1577 } 1578 }); 1579 mediaPlayer.start(); 1580 } catch (IOException ex) { 1581 Log.w(TAG, "MediaPlayer IOException: "+ex); 1582 } catch (IllegalArgumentException ex) { 1583 Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex); 1584 } catch (IllegalStateException ex) { 1585 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); 1586 } 1587 } 1588 } 1589 } 1590 } 1591 1592 private void cleanupPlayer(MediaPlayer mp) { 1593 if (mp != null) { 1594 try { 1595 mp.stop(); 1596 mp.release(); 1597 } catch (IllegalStateException ex) { 1598 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); 1599 } 1600 } 1601 } 1602 1603 @Override 1604 public void handleMessage(Message msg) { 1605 int baseMsgWhat = getMsgBase(msg.what); 1606 1607 switch (baseMsgWhat) { 1608 1609 case MSG_SET_SYSTEM_VOLUME: 1610 setSystemVolume((VolumeStreamState) msg.obj); 1611 break; 1612 1613 case MSG_PERSIST_VOLUME: 1614 persistVolume((VolumeStreamState) msg.obj, (msg.arg1 != 0), (msg.arg2 != 0)); 1615 break; 1616 1617 case MSG_PERSIST_RINGER_MODE: 1618 persistRingerMode(); 1619 break; 1620 1621 case MSG_PERSIST_VIBRATE_SETTING: 1622 persistVibrateSetting(); 1623 break; 1624 1625 case MSG_MEDIA_SERVER_DIED: 1626 // Force creation of new IAudioflinger interface 1627 if (!mMediaServerOk) { 1628 Log.e(TAG, "Media server died."); 1629 AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC); 1630 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0, 1631 null, 500); 1632 } 1633 break; 1634 1635 case MSG_MEDIA_SERVER_STARTED: 1636 Log.e(TAG, "Media server started."); 1637 // Restore device connection states 1638 Set set = mConnectedDevices.entrySet(); 1639 Iterator i = set.iterator(); 1640 while(i.hasNext()){ 1641 Map.Entry device = (Map.Entry)i.next(); 1642 AudioSystem.setDeviceConnectionState(((Integer)device.getKey()).intValue(), 1643 AudioSystem.DEVICE_STATE_AVAILABLE, 1644 (String)device.getValue()); 1645 } 1646 1647 // Restore call state 1648 AudioSystem.setPhoneState(mMode); 1649 1650 // Restore forced usage for communcations and record 1651 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm); 1652 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm); 1653 1654 // Restore stream volumes 1655 int numStreamTypes = AudioSystem.getNumStreamTypes(); 1656 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 1657 int index; 1658 VolumeStreamState streamState = mStreamStates[streamType]; 1659 AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10); 1660 if (streamState.muteCount() == 0) { 1661 index = streamState.mIndex; 1662 } else { 1663 index = 0; 1664 } 1665 setStreamVolumeIndex(streamType, index); 1666 } 1667 1668 // Restore ringer mode 1669 setRingerModeInt(getRingerMode(), false); 1670 break; 1671 1672 case MSG_PLAY_SOUND_EFFECT: 1673 playSoundEffect(msg.arg1, msg.arg2); 1674 break; 1675 1676 case MSG_BTA2DP_DOCK_TIMEOUT: 1677 // msg.obj == address of BTA2DP device 1678 makeA2dpDeviceUnavailableNow( (String) msg.obj ); 1679 break; 1680 } 1681 } 1682 } 1683 1684 private class SettingsObserver extends ContentObserver { 1685 1686 SettingsObserver() { 1687 super(new Handler()); 1688 mContentResolver.registerContentObserver(Settings.System.getUriFor( 1689 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this); 1690 mContentResolver.registerContentObserver(Settings.System.getUriFor( 1691 Settings.System.NOTIFICATIONS_USE_RING_VOLUME), false, this); 1692 } 1693 1694 @Override 1695 public void onChange(boolean selfChange) { 1696 super.onChange(selfChange); 1697 synchronized (mSettingsLock) { 1698 int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver, 1699 Settings.System.MODE_RINGER_STREAMS_AFFECTED, 1700 0); 1701 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) { 1702 /* 1703 * Ensure all stream types that should be affected by ringer mode 1704 * are in the proper state. 1705 */ 1706 mRingerModeAffectedStreams = ringerModeAffectedStreams; 1707 setRingerModeInt(getRingerMode(), false); 1708 } 1709 1710 int notificationsUseRingVolume = Settings.System.getInt(mContentResolver, 1711 Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1712 1); 1713 if (notificationsUseRingVolume != mNotificationsUseRingVolume) { 1714 mNotificationsUseRingVolume = notificationsUseRingVolume; 1715 if (mNotificationsUseRingVolume == 1) { 1716 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING; 1717 mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName( 1718 System.VOLUME_SETTINGS[AudioSystem.STREAM_RING]); 1719 } else { 1720 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION; 1721 mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName( 1722 System.VOLUME_SETTINGS[AudioSystem.STREAM_NOTIFICATION]); 1723 // Persist notification volume volume as it was not persisted while aliased to ring volume 1724 // and persist with no delay as there might be registered observers of the persisted 1725 // notification volume. 1726 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, AudioSystem.STREAM_NOTIFICATION, 1727 SENDMSG_REPLACE, 1, 1, mStreamStates[AudioSystem.STREAM_NOTIFICATION], 0); 1728 } 1729 } 1730 } 1731 } 1732 } 1733 1734 private void makeA2dpDeviceAvailable(String address) { 1735 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 1736 AudioSystem.DEVICE_STATE_AVAILABLE, 1737 address); 1738 // Reset A2DP suspend state each time a new sink is connected 1739 AudioSystem.setParameters("A2dpSuspended=false"); 1740 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP), 1741 address); 1742 } 1743 1744 private void makeA2dpDeviceUnavailableNow(String address) { 1745 Intent noisyIntent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY); 1746 mContext.sendBroadcast(noisyIntent); 1747 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 1748 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1749 address); 1750 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP); 1751 } 1752 1753 private void makeA2dpDeviceUnavailableLater(String address) { 1754 // prevent any activity on the A2DP audio output to avoid unwanted 1755 // reconnection of the sink. 1756 AudioSystem.setParameters("A2dpSuspended=true"); 1757 // the device will be made unavailable later, so consider it disconnected right away 1758 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP); 1759 // send the delayed message to make the device unavailable later 1760 Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address); 1761 mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS); 1762 1763 } 1764 1765 private void cancelA2dpDeviceTimeout() { 1766 mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT); 1767 } 1768 1769 private boolean hasScheduledA2dpDockTimeout() { 1770 return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT); 1771 } 1772 1773 /* cache of the address of the last dock the device was connected to */ 1774 private String mDockAddress; 1775 1776 /** 1777 * Receiver for misc intent broadcasts the Phone app cares about. 1778 */ 1779 private class AudioServiceBroadcastReceiver extends BroadcastReceiver { 1780 @Override 1781 public void onReceive(Context context, Intent intent) { 1782 String action = intent.getAction(); 1783 1784 if (action.equals(Intent.ACTION_DOCK_EVENT)) { 1785 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 1786 Intent.EXTRA_DOCK_STATE_UNDOCKED); 1787 int config; 1788 switch (dockState) { 1789 case Intent.EXTRA_DOCK_STATE_DESK: 1790 config = AudioSystem.FORCE_BT_DESK_DOCK; 1791 break; 1792 case Intent.EXTRA_DOCK_STATE_CAR: 1793 config = AudioSystem.FORCE_BT_CAR_DOCK; 1794 break; 1795 case Intent.EXTRA_DOCK_STATE_UNDOCKED: 1796 default: 1797 config = AudioSystem.FORCE_NONE; 1798 } 1799 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config); 1800 } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) { 1801 int state = intent.getIntExtra(BluetoothA2dp.EXTRA_SINK_STATE, 1802 BluetoothA2dp.STATE_DISCONNECTED); 1803 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 1804 String address = btDevice.getAddress(); 1805 boolean isConnected = (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) && 1806 ((String)mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)).equals(address)); 1807 1808 if (isConnected && 1809 state != BluetoothA2dp.STATE_CONNECTED && state != BluetoothA2dp.STATE_PLAYING) { 1810 if (btDevice.isBluetoothDock()) { 1811 if (state == BluetoothA2dp.STATE_DISCONNECTED) { 1812 // introduction of a delay for transient disconnections of docks when 1813 // power is rapidly turned off/on, this message will be canceled if 1814 // we reconnect the dock under a preset delay 1815 makeA2dpDeviceUnavailableLater(address); 1816 // the next time isConnected is evaluated, it will be false for the dock 1817 } 1818 } else { 1819 makeA2dpDeviceUnavailableNow(address); 1820 } 1821 } else if (!isConnected && 1822 (state == BluetoothA2dp.STATE_CONNECTED || 1823 state == BluetoothA2dp.STATE_PLAYING)) { 1824 if (btDevice.isBluetoothDock()) { 1825 // this could be a reconnection after a transient disconnection 1826 cancelA2dpDeviceTimeout(); 1827 mDockAddress = address; 1828 } else { 1829 // this could be a connection of another A2DP device before the timeout of 1830 // a dock: cancel the dock timeout, and make the dock unavailable now 1831 if(hasScheduledA2dpDockTimeout()) { 1832 cancelA2dpDeviceTimeout(); 1833 makeA2dpDeviceUnavailableNow(mDockAddress); 1834 } 1835 } 1836 makeA2dpDeviceAvailable(address); 1837 } 1838 } else if (action.equals(BluetoothHeadset.ACTION_STATE_CHANGED)) { 1839 int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, 1840 BluetoothHeadset.STATE_ERROR); 1841 int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO; 1842 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 1843 String address = null; 1844 if (btDevice != null) { 1845 address = btDevice.getAddress(); 1846 BluetoothClass btClass = btDevice.getBluetoothClass(); 1847 if (btClass != null) { 1848 switch (btClass.getDeviceClass()) { 1849 case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET: 1850 case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE: 1851 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 1852 break; 1853 case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO: 1854 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 1855 break; 1856 } 1857 } 1858 } 1859 1860 boolean isConnected = (mConnectedDevices.containsKey(device) && 1861 ((String)mConnectedDevices.get(device)).equals(address)); 1862 1863 if (isConnected && state != BluetoothHeadset.STATE_CONNECTED) { 1864 AudioSystem.setDeviceConnectionState(device, 1865 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1866 address); 1867 mConnectedDevices.remove(device); 1868 mBluetoothHeadsetConnected = false; 1869 clearAllScoClients(); 1870 } else if (!isConnected && state == BluetoothHeadset.STATE_CONNECTED) { 1871 AudioSystem.setDeviceConnectionState(device, 1872 AudioSystem.DEVICE_STATE_AVAILABLE, 1873 address); 1874 mConnectedDevices.put(new Integer(device), address); 1875 mBluetoothHeadsetConnected = true; 1876 } 1877 } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { 1878 int state = intent.getIntExtra("state", 0); 1879 int microphone = intent.getIntExtra("microphone", 0); 1880 1881 if (microphone != 0) { 1882 boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET); 1883 if (state == 0 && isConnected) { 1884 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET, 1885 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1886 ""); 1887 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET); 1888 } else if (state == 1 && !isConnected) { 1889 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET, 1890 AudioSystem.DEVICE_STATE_AVAILABLE, 1891 ""); 1892 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), ""); 1893 } 1894 } else { 1895 boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE); 1896 if (state == 0 && isConnected) { 1897 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, 1898 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1899 ""); 1900 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE); 1901 } else if (state == 1 && !isConnected) { 1902 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, 1903 AudioSystem.DEVICE_STATE_AVAILABLE, 1904 ""); 1905 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), ""); 1906 } 1907 } 1908 } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) { 1909 int state = intent.getIntExtra(BluetoothHeadset.EXTRA_AUDIO_STATE, 1910 BluetoothHeadset.STATE_ERROR); 1911 synchronized (mScoClients) { 1912 if (!mScoClients.isEmpty()) { 1913 switch (state) { 1914 case BluetoothHeadset.AUDIO_STATE_CONNECTED: 1915 state = AudioManager.SCO_AUDIO_STATE_CONNECTED; 1916 break; 1917 case BluetoothHeadset.AUDIO_STATE_DISCONNECTED: 1918 state = AudioManager.SCO_AUDIO_STATE_DISCONNECTED; 1919 break; 1920 default: 1921 state = AudioManager.SCO_AUDIO_STATE_ERROR; 1922 break; 1923 } 1924 if (state != AudioManager.SCO_AUDIO_STATE_ERROR) { 1925 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); 1926 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state); 1927 mContext.sendStickyBroadcast(newIntent); 1928 } 1929 } 1930 } 1931 } 1932 } 1933 } 1934 1935 //========================================================================================== 1936 // AudioFocus 1937 //========================================================================================== 1938 1939 /* constant to identify focus stack entry that is used to hold the focus while the phone 1940 * is ringing or during a call 1941 */ 1942 private final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls"; 1943 1944 private final static Object mAudioFocusLock = new Object(); 1945 1946 private PhoneStateListener mPhoneStateListener = new PhoneStateListener() { 1947 @Override 1948 public void onCallStateChanged(int state, String incomingNumber) { 1949 if (state == TelephonyManager.CALL_STATE_RINGING) { 1950 //Log.v(TAG, " CALL_STATE_RINGING"); 1951 int ringVolume = AudioService.this.getStreamVolume(AudioManager.STREAM_RING); 1952 if (ringVolume > 0) { 1953 requestAudioFocus(AudioManager.STREAM_RING, 1954 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT, 1955 null, null /* both allowed to be null only for this clientId */, 1956 IN_VOICE_COMM_FOCUS_ID /*clientId*/); 1957 } 1958 } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) { 1959 //Log.v(TAG, " CALL_STATE_OFFHOOK"); 1960 requestAudioFocus(AudioManager.STREAM_RING, 1961 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT, 1962 null, null /* both allowed to be null only for this clientId */, 1963 IN_VOICE_COMM_FOCUS_ID /*clientId*/); 1964 } else if (state == TelephonyManager.CALL_STATE_IDLE) { 1965 //Log.v(TAG, " CALL_STATE_IDLE"); 1966 abandonAudioFocus(null, IN_VOICE_COMM_FOCUS_ID); 1967 } 1968 } 1969 }; 1970 1971 private void notifyTopOfAudioFocusStack() { 1972 // notify the top of the stack it gained focus 1973 if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) { 1974 if (canReassignAudioFocus()) { 1975 try { 1976 mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange( 1977 AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId); 1978 } catch (RemoteException e) { 1979 Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e); 1980 e.printStackTrace(); 1981 } 1982 } 1983 } 1984 } 1985 1986 private static class FocusStackEntry { 1987 public int mStreamType = -1;// no stream type 1988 public boolean mIsTransportControlReceiver = false; 1989 public IAudioFocusDispatcher mFocusDispatcher = null; 1990 public IBinder mSourceRef = null; 1991 public String mClientId; 1992 public int mFocusChangeType; 1993 1994 public FocusStackEntry() { 1995 } 1996 1997 public FocusStackEntry(int streamType, int duration, boolean isTransportControlReceiver, 1998 IAudioFocusDispatcher afl, IBinder source, String id) { 1999 mStreamType = streamType; 2000 mIsTransportControlReceiver = isTransportControlReceiver; 2001 mFocusDispatcher = afl; 2002 mSourceRef = source; 2003 mClientId = id; 2004 mFocusChangeType = duration; 2005 } 2006 } 2007 2008 private Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>(); 2009 2010 /** 2011 * Helper function: 2012 * Display in the log the current entries in the audio focus stack 2013 */ 2014 private void dumpFocusStack(PrintWriter pw) { 2015 pw.println("\nAudio Focus stack entries:"); 2016 synchronized(mAudioFocusLock) { 2017 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); 2018 while(stackIterator.hasNext()) { 2019 FocusStackEntry fse = stackIterator.next(); 2020 pw.println(" source:" + fse.mSourceRef + " -- client: " + fse.mClientId 2021 + " -- duration: " +fse.mFocusChangeType); 2022 } 2023 } 2024 } 2025 2026 /** 2027 * Helper function: 2028 * Remove a focus listener from the focus stack. 2029 * @param focusListenerToRemove the focus listener 2030 * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding 2031 * focus, notify the next item in the stack it gained focus. 2032 */ 2033 private void removeFocusStackEntry(String clientToRemove, boolean signal) { 2034 // is the current top of the focus stack abandoning focus? (because of death or request) 2035 if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove)) 2036 { 2037 //Log.i(TAG, " removeFocusStackEntry() removing top of stack"); 2038 mFocusStack.pop(); 2039 if (signal) { 2040 // notify the new top of the stack it gained focus 2041 notifyTopOfAudioFocusStack(); 2042 } 2043 } else { 2044 // focus is abandoned by a client that's not at the top of the stack, 2045 // no need to update focus. 2046 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); 2047 while(stackIterator.hasNext()) { 2048 FocusStackEntry fse = (FocusStackEntry)stackIterator.next(); 2049 if(fse.mClientId.equals(clientToRemove)) { 2050 Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for " 2051 + fse.mClientId); 2052 mFocusStack.remove(fse); 2053 } 2054 } 2055 } 2056 } 2057 2058 /** 2059 * Helper function: 2060 * Remove focus listeners from the focus stack for a particular client. 2061 */ 2062 private void removeFocusStackEntryForClient(IBinder cb) { 2063 // is the owner of the audio focus part of the client to remove? 2064 boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() && 2065 mFocusStack.peek().mSourceRef.equals(cb); 2066 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); 2067 while(stackIterator.hasNext()) { 2068 FocusStackEntry fse = (FocusStackEntry)stackIterator.next(); 2069 if(fse.mSourceRef.equals(cb)) { 2070 Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for " 2071 + fse.mClientId); 2072 mFocusStack.remove(fse); 2073 } 2074 } 2075 if (isTopOfStackForClientToRemove) { 2076 // we removed an entry at the top of the stack: 2077 // notify the new top of the stack it gained focus. 2078 notifyTopOfAudioFocusStack(); 2079 } 2080 } 2081 2082 /** 2083 * Helper function: 2084 * Returns true if the system is in a state where the focus can be reevaluated, false otherwise. 2085 */ 2086 private boolean canReassignAudioFocus() { 2087 // focus requests are rejected during a phone call or when the phone is ringing 2088 // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus 2089 if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) { 2090 return false; 2091 } 2092 return true; 2093 } 2094 2095 /** 2096 * Inner class to monitor audio focus client deaths, and remove them from the audio focus 2097 * stack if necessary. 2098 */ 2099 private class AudioFocusDeathHandler implements IBinder.DeathRecipient { 2100 private IBinder mCb; // To be notified of client's death 2101 2102 AudioFocusDeathHandler(IBinder cb) { 2103 mCb = cb; 2104 } 2105 2106 public void binderDied() { 2107 synchronized(mAudioFocusLock) { 2108 Log.w(TAG, " AudioFocus audio focus client died"); 2109 removeFocusStackEntryForClient(mCb); 2110 } 2111 } 2112 2113 public IBinder getBinder() { 2114 return mCb; 2115 } 2116 } 2117 2118 2119 /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */ 2120 public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb, 2121 IAudioFocusDispatcher fd, String clientId) { 2122 Log.i(TAG, " AudioFocus requestAudioFocus() from " + clientId); 2123 // the main stream type for the audio focus request is currently not used. It may 2124 // potentially be used to handle multiple stream type-dependent audio focuses. 2125 2126 // we need a valid binder callback for clients other than the AudioService's phone 2127 // state listener 2128 if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId) && ((cb == null) || !cb.pingBinder())) { 2129 Log.i(TAG, " AudioFocus DOA client for requestAudioFocus(), exiting"); 2130 return AudioManager.AUDIOFOCUS_REQUEST_FAILED; 2131 } 2132 2133 synchronized(mAudioFocusLock) { 2134 if (!canReassignAudioFocus()) { 2135 return AudioManager.AUDIOFOCUS_REQUEST_FAILED; 2136 } 2137 2138 if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) { 2139 // if focus is already owned by this client and the reason for acquiring the focus 2140 // hasn't changed, don't do anything 2141 if (mFocusStack.peek().mFocusChangeType == focusChangeHint) { 2142 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; 2143 } 2144 // the reason for the audio focus request has changed: remove the current top of 2145 // stack and respond as if we had a new focus owner 2146 mFocusStack.pop(); 2147 } 2148 2149 // notify current top of stack it is losing focus 2150 if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) { 2151 try { 2152 mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange( 2153 -1 * focusChangeHint, // loss and gain codes are inverse of each other 2154 mFocusStack.peek().mClientId); 2155 } catch (RemoteException e) { 2156 Log.e(TAG, " Failure to signal loss of focus due to "+ e); 2157 e.printStackTrace(); 2158 } 2159 } 2160 2161 // focus requester might already be somewhere below in the stack, remove it 2162 removeFocusStackEntry(clientId, false); 2163 2164 // push focus requester at the top of the audio focus stack 2165 mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, false, fd, cb, 2166 clientId)); 2167 }//synchronized(mAudioFocusLock) 2168 2169 // handle the potential premature death of the new holder of the focus 2170 // (premature death == death before abandoning focus) for a client which is not the 2171 // AudioService's phone state listener 2172 if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId)) { 2173 // Register for client death notification 2174 AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb); 2175 try { 2176 cb.linkToDeath(afdh, 0); 2177 } catch (RemoteException e) { 2178 // client has already died! 2179 Log.w(TAG, "AudioFocus requestAudioFocus() could not link to "+cb+" binder death"); 2180 } 2181 } 2182 2183 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; 2184 } 2185 2186 /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */ 2187 public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) { 2188 Log.i(TAG, " AudioFocus abandonAudioFocus() from " + clientId); 2189 try { 2190 // this will take care of notifying the new focus owner if needed 2191 synchronized(mAudioFocusLock) { 2192 removeFocusStackEntry(clientId, true); 2193 } 2194 } catch (java.util.ConcurrentModificationException cme) { 2195 // Catching this exception here is temporary. It is here just to prevent 2196 // a crash seen when the "Silent" notification is played. This is believed to be fixed 2197 // but this try catch block is left just to be safe. 2198 Log.e(TAG, "FATAL EXCEPTION AudioFocus abandonAudioFocus() caused " + cme); 2199 cme.printStackTrace(); 2200 } 2201 2202 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; 2203 } 2204 2205 2206 public void unregisterAudioFocusClient(String clientId) { 2207 synchronized(mAudioFocusLock) { 2208 removeFocusStackEntry(clientId, false); 2209 } 2210 } 2211 2212 2213 //========================================================================================== 2214 // RemoteControl 2215 //========================================================================================== 2216 /** 2217 * Receiver for media button intents. Handles the dispatching of the media button event 2218 * to one of the registered listeners, or if there was none, resumes the intent broadcast 2219 * to the rest of the system. 2220 */ 2221 private class MediaButtonBroadcastReceiver extends BroadcastReceiver { 2222 @Override 2223 public void onReceive(Context context, Intent intent) { 2224 String action = intent.getAction(); 2225 if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) { 2226 return; 2227 } 2228 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); 2229 if (event != null) { 2230 // if in a call or ringing, do not break the current phone app behavior 2231 // TODO modify this to let the phone app specifically get the RC focus 2232 // add modify the phone app to take advantage of the new API 2233 if ((getMode() == AudioSystem.MODE_IN_CALL) || 2234 (getMode() == AudioSystem.MODE_RINGTONE)) { 2235 return; 2236 } 2237 synchronized(mRCStack) { 2238 if (!mRCStack.empty()) { 2239 // create a new intent specifically aimed at the current registered listener 2240 Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); 2241 targetedIntent.putExtras(intent.getExtras()); 2242 targetedIntent.setComponent(mRCStack.peek().mReceiverComponent); 2243 // trap the current broadcast 2244 abortBroadcast(); 2245 //Log.v(TAG, " Sending intent" + targetedIntent); 2246 context.sendBroadcast(targetedIntent, null); 2247 } 2248 } 2249 } 2250 } 2251 } 2252 2253 private static class RemoteControlStackEntry { 2254 public ComponentName mReceiverComponent;// always non null 2255 // TODO implement registration expiration? 2256 //public int mRegistrationTime; 2257 2258 public RemoteControlStackEntry() { 2259 } 2260 2261 public RemoteControlStackEntry(ComponentName r) { 2262 mReceiverComponent = r; 2263 } 2264 } 2265 2266 private Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>(); 2267 2268 /** 2269 * Helper function: 2270 * Display in the log the current entries in the remote control focus stack 2271 */ 2272 private void dumpRCStack(PrintWriter pw) { 2273 pw.println("\nRemote Control stack entries:"); 2274 synchronized(mRCStack) { 2275 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 2276 while(stackIterator.hasNext()) { 2277 RemoteControlStackEntry fse = stackIterator.next(); 2278 pw.println(" receiver:" + fse.mReceiverComponent); 2279 } 2280 } 2281 } 2282 2283 /** 2284 * Helper function: 2285 * Set the new remote control receiver at the top of the RC focus stack 2286 */ 2287 private void pushMediaButtonReceiver(ComponentName newReceiver) { 2288 // already at top of stack? 2289 if (!mRCStack.empty() && mRCStack.peek().mReceiverComponent.equals(newReceiver)) { 2290 return; 2291 } 2292 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 2293 while(stackIterator.hasNext()) { 2294 RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next(); 2295 if(rcse.mReceiverComponent.equals(newReceiver)) { 2296 mRCStack.remove(rcse); 2297 break; 2298 } 2299 } 2300 mRCStack.push(new RemoteControlStackEntry(newReceiver)); 2301 } 2302 2303 /** 2304 * Helper function: 2305 * Remove the remote control receiver from the RC focus stack 2306 */ 2307 private void removeMediaButtonReceiver(ComponentName newReceiver) { 2308 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); 2309 while(stackIterator.hasNext()) { 2310 RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next(); 2311 if(rcse.mReceiverComponent.equals(newReceiver)) { 2312 mRCStack.remove(rcse); 2313 break; 2314 } 2315 } 2316 } 2317 2318 2319 /** see AudioManager.registerMediaButtonEventReceiver(ComponentName eventReceiver) */ 2320 public void registerMediaButtonEventReceiver(ComponentName eventReceiver) { 2321 Log.i(TAG, " Remote Control registerMediaButtonEventReceiver() for " + eventReceiver); 2322 2323 synchronized(mRCStack) { 2324 pushMediaButtonReceiver(eventReceiver); 2325 } 2326 } 2327 2328 /** see AudioManager.unregisterMediaButtonEventReceiver(ComponentName eventReceiver) */ 2329 public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) { 2330 Log.i(TAG, " Remote Control unregisterMediaButtonEventReceiver() for " + eventReceiver); 2331 2332 synchronized(mRCStack) { 2333 removeMediaButtonReceiver(eventReceiver); 2334 } 2335 } 2336 2337 2338 @Override 2339 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2340 // TODO probably a lot more to do here than just the audio focus and remote control stacks 2341 dumpFocusStack(pw); 2342 dumpRCStack(pw); 2343 } 2344 2345 2346} 2347