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