AudioService.java revision 1c633fc89bae9bf0af6fe643ac7ad2e744f27bed
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.content.BroadcastReceiver; 21import android.content.ContentResolver; 22import android.content.Context; 23import android.content.Intent; 24import android.content.IntentFilter; 25import android.bluetooth.BluetoothA2dp; 26import android.bluetooth.BluetoothClass; 27import android.bluetooth.BluetoothDevice; 28import android.bluetooth.BluetoothHeadset; 29 30import android.content.pm.PackageManager; 31import android.database.ContentObserver; 32import android.media.MediaPlayer.OnCompletionListener; 33import android.media.MediaPlayer.OnErrorListener; 34import android.os.Binder; 35import android.os.Environment; 36import android.os.Handler; 37import android.os.IBinder; 38import android.os.Looper; 39import android.os.Message; 40import android.os.RemoteException; 41import android.os.ServiceManager; 42import android.provider.Settings; 43import android.provider.Settings.System; 44import android.util.Log; 45import android.view.VolumePanel; 46import android.os.SystemProperties; 47 48import com.android.internal.telephony.ITelephony; 49 50import java.io.IOException; 51import java.util.ArrayList; 52import java.util.HashMap; 53import java.util.Iterator; 54import java.util.Map; 55import java.util.Set; 56 57 58/** 59 * The implementation of the volume manager service. 60 * <p> 61 * This implementation focuses on delivering a responsive UI. Most methods are 62 * asynchronous to external calls. For example, the task of setting a volume 63 * will update our internal state, but in a separate thread will set the system 64 * volume and later persist to the database. Similarly, setting the ringer mode 65 * will update the state and broadcast a change and in a separate thread later 66 * persist the ringer mode. 67 * 68 * @hide 69 */ 70public class AudioService extends IAudioService.Stub { 71 72 private static final String TAG = "AudioService"; 73 74 /** How long to delay before persisting a change in volume/ringer mode. */ 75 private static final int PERSIST_DELAY = 3000; 76 77 private Context mContext; 78 private ContentResolver mContentResolver; 79 80 /** The UI */ 81 private VolumePanel mVolumePanel; 82 83 // sendMsg() flags 84 /** Used when a message should be shared across all stream types. */ 85 private static final int SHARED_MSG = -1; 86 /** If the msg is already queued, replace it with this one. */ 87 private static final int SENDMSG_REPLACE = 0; 88 /** If the msg is already queued, ignore this one and leave the old. */ 89 private static final int SENDMSG_NOOP = 1; 90 /** If the msg is already queued, queue this one and leave the old. */ 91 private static final int SENDMSG_QUEUE = 2; 92 93 // AudioHandler message.whats 94 private static final int MSG_SET_SYSTEM_VOLUME = 0; 95 private static final int MSG_PERSIST_VOLUME = 1; 96 private static final int MSG_PERSIST_RINGER_MODE = 3; 97 private static final int MSG_PERSIST_VIBRATE_SETTING = 4; 98 private static final int MSG_MEDIA_SERVER_DIED = 5; 99 private static final int MSG_MEDIA_SERVER_STARTED = 6; 100 private static final int MSG_PLAY_SOUND_EFFECT = 7; 101 102 /** @see AudioSystemThread */ 103 private AudioSystemThread mAudioSystemThread; 104 /** @see AudioHandler */ 105 private AudioHandler mAudioHandler; 106 /** @see VolumeStreamState */ 107 private VolumeStreamState[] mStreamStates; 108 private SettingsObserver mSettingsObserver; 109 110 private int mMode; 111 private Object mSettingsLock = new Object(); 112 private boolean mMediaServerOk; 113 114 /** cached value of the BT dock address to recognize undocking events */ 115 private static String sBtDockAddress; 116 117 private SoundPool mSoundPool; 118 private Object mSoundEffectsLock = new Object(); 119 private static final int NUM_SOUNDPOOL_CHANNELS = 4; 120 private static final int SOUND_EFFECT_VOLUME = 1000; 121 122 /* Sound effect file names */ 123 private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/"; 124 private static final String[] SOUND_EFFECT_FILES = new String[] { 125 "Effect_Tick.ogg", 126 "KeypressStandard.ogg", 127 "KeypressSpacebar.ogg", 128 "KeypressDelete.ogg", 129 "KeypressReturn.ogg" 130 }; 131 132 /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to 133 * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect 134 * uses soundpool (second column) */ 135 private int[][] SOUND_EFFECT_FILES_MAP = new int[][] { 136 {0, -1}, // FX_KEY_CLICK 137 {0, -1}, // FX_FOCUS_NAVIGATION_UP 138 {0, -1}, // FX_FOCUS_NAVIGATION_DOWN 139 {0, -1}, // FX_FOCUS_NAVIGATION_LEFT 140 {0, -1}, // FX_FOCUS_NAVIGATION_RIGHT 141 {1, -1}, // FX_KEYPRESS_STANDARD 142 {2, -1}, // FX_KEYPRESS_SPACEBAR 143 {3, -1}, // FX_FOCUS_DELETE 144 {4, -1} // FX_FOCUS_RETURN 145 }; 146 147 /** @hide Maximum volume index values for audio streams */ 148 private int[] MAX_STREAM_VOLUME = new int[] { 149 5, // STREAM_VOICE_CALL 150 7, // STREAM_SYSTEM 151 7, // STREAM_RING 152 15, // STREAM_MUSIC 153 7, // STREAM_ALARM 154 7, // STREAM_NOTIFICATION 155 15, // STREAM_BLUETOOTH_SCO 156 7, // STREAM_SYSTEM_ENFORCED 157 15, // STREAM_DTMF 158 15 // STREAM_TTS 159 }; 160 /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings 161 * of another stream: This avoids multiplying the volume settings for hidden 162 * stream types that follow other stream behavior for volume settings 163 * NOTE: do not create loops in aliases! */ 164 private int[] STREAM_VOLUME_ALIAS = new int[] { 165 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL 166 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM 167 AudioSystem.STREAM_RING, // STREAM_RING 168 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC 169 AudioSystem.STREAM_ALARM, // STREAM_ALARM 170 AudioSystem.STREAM_NOTIFICATION, // STREAM_NOTIFICATION 171 AudioSystem.STREAM_VOICE_CALL, // STREAM_BLUETOOTH_SCO 172 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM_ENFORCED 173 AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF 174 AudioSystem.STREAM_MUSIC // STREAM_TTS 175 }; 176 177 private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() { 178 public void onError(int error) { 179 switch (error) { 180 case AudioSystem.AUDIO_STATUS_SERVER_DIED: 181 if (mMediaServerOk) { 182 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0, 183 null, 1500); 184 mMediaServerOk = false; 185 } 186 break; 187 case AudioSystem.AUDIO_STATUS_OK: 188 if (!mMediaServerOk) { 189 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0, 190 null, 0); 191 mMediaServerOk = true; 192 } 193 break; 194 default: 195 break; 196 } 197 } 198 }; 199 200 /** 201 * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL}, 202 * {@link AudioManager#RINGER_MODE_SILENT}, or 203 * {@link AudioManager#RINGER_MODE_VIBRATE}. 204 */ 205 private int mRingerMode; 206 207 /** @see System#MODE_RINGER_STREAMS_AFFECTED */ 208 private int mRingerModeAffectedStreams; 209 210 /** @see System#MUTE_STREAMS_AFFECTED */ 211 private int mMuteAffectedStreams; 212 213 /** 214 * Has multiple bits per vibrate type to indicate the type's vibrate 215 * setting. See {@link #setVibrateSetting(int, int)}. 216 * <p> 217 * NOTE: This is not the final decision of whether vibrate is on/off for the 218 * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}. 219 */ 220 private int mVibrateSetting; 221 222 /** @see System#NOTIFICATIONS_USE_RING_VOLUME */ 223 private int mNotificationsUseRingVolume; 224 225 // Broadcast receiver for device connections intent broadcasts 226 private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver(); 227 228 // Devices currently connected 229 private HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>(); 230 231 // Forced device usage for communications 232 private int mForcedUseForComm; 233 234 /////////////////////////////////////////////////////////////////////////// 235 // Construction 236 /////////////////////////////////////////////////////////////////////////// 237 238 /** @hide */ 239 public AudioService(Context context) { 240 mContext = context; 241 mContentResolver = context.getContentResolver(); 242 243 // Intialized volume 244 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt( 245 "ro.config.vc_call_vol_steps", 246 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]); 247 248 mVolumePanel = new VolumePanel(context, this); 249 mSettingsObserver = new SettingsObserver(); 250 mMode = AudioSystem.MODE_NORMAL; 251 mForcedUseForComm = AudioSystem.FORCE_NONE; 252 createAudioSystemThread(); 253 readPersistedSettings(); 254 createStreamStates(); 255 mMediaServerOk = true; 256 AudioSystem.setErrorCallback(mAudioSystemCallback); 257 loadSoundEffects(); 258 259 // Register for device connection intent broadcasts. 260 IntentFilter intentFilter = 261 new IntentFilter(Intent.ACTION_HEADSET_PLUG); 262 intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED); 263 intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED); 264 context.registerReceiver(mReceiver, intentFilter); 265 266 } 267 268 private void createAudioSystemThread() { 269 mAudioSystemThread = new AudioSystemThread(); 270 mAudioSystemThread.start(); 271 waitForAudioHandlerCreation(); 272 } 273 274 /** Waits for the volume handler to be created by the other thread. */ 275 private void waitForAudioHandlerCreation() { 276 synchronized(this) { 277 while (mAudioHandler == null) { 278 try { 279 // Wait for mAudioHandler to be set by the other thread 280 wait(); 281 } catch (InterruptedException e) { 282 Log.e(TAG, "Interrupted while waiting on volume handler."); 283 } 284 } 285 } 286 } 287 288 private void createStreamStates() { 289 int numStreamTypes = AudioSystem.getNumStreamTypes(); 290 VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes]; 291 292 for (int i = 0; i < numStreamTypes; i++) { 293 streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i); 294 } 295 296 // Correct stream index values for streams with aliases 297 for (int i = 0; i < numStreamTypes; i++) { 298 if (STREAM_VOLUME_ALIAS[i] != i) { 299 int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i); 300 streams[i].mIndex = streams[i].getValidIndex(index); 301 setStreamVolumeIndex(i, index); 302 index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i); 303 streams[i].mLastAudibleIndex = streams[i].getValidIndex(index); 304 } 305 } 306 } 307 308 private void readPersistedSettings() { 309 final ContentResolver cr = mContentResolver; 310 311 mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL); 312 313 mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0); 314 315 mRingerModeAffectedStreams = Settings.System.getInt(cr, 316 Settings.System.MODE_RINGER_STREAMS_AFFECTED, 317 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)| 318 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED))); 319 320 mMuteAffectedStreams = System.getInt(cr, 321 System.MUTE_STREAMS_AFFECTED, 322 ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM))); 323 324 mNotificationsUseRingVolume = System.getInt(cr, 325 Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1); 326 327 if (mNotificationsUseRingVolume == 1) { 328 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING; 329 } 330 // Each stream will read its own persisted settings 331 332 // Broadcast the sticky intent 333 broadcastRingerMode(); 334 335 // Broadcast vibrate settings 336 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); 337 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION); 338 } 339 340 private void setStreamVolumeIndex(int stream, int index) { 341 AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10); 342 } 343 344 private int rescaleIndex(int index, int srcStream, int dstStream) { 345 return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex(); 346 } 347 348 /////////////////////////////////////////////////////////////////////////// 349 // IPC methods 350 /////////////////////////////////////////////////////////////////////////// 351 352 /** @see AudioManager#adjustVolume(int, int) */ 353 public void adjustVolume(int direction, int flags) { 354 adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags); 355 } 356 357 /** @see AudioManager#adjustVolume(int, int, int) */ 358 public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) { 359 360 int streamType = getActiveStreamType(suggestedStreamType); 361 362 // Don't play sound on other streams 363 if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) { 364 flags &= ~AudioManager.FLAG_PLAY_SOUND; 365 } 366 367 adjustStreamVolume(streamType, direction, flags); 368 } 369 370 /** @see AudioManager#adjustStreamVolume(int, int, int) */ 371 public void adjustStreamVolume(int streamType, int direction, int flags) { 372 ensureValidDirection(direction); 373 ensureValidStreamType(streamType); 374 375 376 VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]]; 377 final int oldIndex = streamState.mIndex; 378 boolean adjustVolume = true; 379 380 // If either the client forces allowing ringer modes for this adjustment, 381 // or the stream type is one that is affected by ringer modes 382 if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0 383 || streamType == AudioSystem.STREAM_RING) { 384 // Check if the ringer mode changes with this volume adjustment. If 385 // it does, it will handle adjusting the volume, so we won't below 386 adjustVolume = checkForRingerModeChange(oldIndex, direction); 387 } 388 389 if (adjustVolume && streamState.adjustIndex(direction)) { 390 // Post message to set system volume (it in turn will post a message 391 // to persist). Do not change volume if stream is muted. 392 if (streamState.muteCount() == 0) { 393 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, STREAM_VOLUME_ALIAS[streamType], SENDMSG_NOOP, 0, 0, 394 streamState, 0); 395 } 396 } 397 398 // UI 399 mVolumePanel.postVolumeChanged(streamType, flags); 400 // Broadcast Intent 401 sendVolumeUpdate(streamType); 402 } 403 404 /** @see AudioManager#setStreamVolume(int, int, int) */ 405 public void setStreamVolume(int streamType, int index, int flags) { 406 ensureValidStreamType(streamType); 407 index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]); 408 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true); 409 410 // UI, etc. 411 mVolumePanel.postVolumeChanged(streamType, flags); 412 // Broadcast Intent 413 sendVolumeUpdate(streamType); 414 } 415 416 private void sendVolumeUpdate(int streamType) { 417 Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION); 418 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType); 419 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, getStreamVolume(streamType)); 420 421 // Currently, sending the intent only when the stream is BLUETOOTH_SCO 422 if (streamType == AudioSystem.STREAM_BLUETOOTH_SCO) { 423 mContext.sendBroadcast(intent); 424 } 425 } 426 427 /** 428 * Sets the stream state's index, and posts a message to set system volume. 429 * This will not call out to the UI. Assumes a valid stream type. 430 * 431 * @param streamType Type of the stream 432 * @param index Desired volume index of the stream 433 * @param force If true, set the volume even if the desired volume is same 434 * as the current volume. 435 * @param lastAudible If true, stores new index as last audible one 436 */ 437 private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) { 438 VolumeStreamState streamState = mStreamStates[streamType]; 439 if (streamState.setIndex(index, lastAudible) || force) { 440 // Post message to set system volume (it in turn will post a message 441 // to persist). Do not change volume if stream is muted. 442 if (streamState.muteCount() == 0) { 443 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0, 444 streamState, 0); 445 } 446 } 447 } 448 449 /** @see AudioManager#setStreamSolo(int, boolean) */ 450 public void setStreamSolo(int streamType, boolean state, IBinder cb) { 451 for (int stream = 0; stream < mStreamStates.length; stream++) { 452 if (!isStreamAffectedByMute(stream) || stream == streamType) continue; 453 // Bring back last audible volume 454 mStreamStates[stream].mute(cb, state); 455 } 456 } 457 458 /** @see AudioManager#setStreamMute(int, boolean) */ 459 public void setStreamMute(int streamType, boolean state, IBinder cb) { 460 if (isStreamAffectedByMute(streamType)) { 461 mStreamStates[streamType].mute(cb, state); 462 } 463 } 464 465 /** @see AudioManager#getStreamVolume(int) */ 466 public int getStreamVolume(int streamType) { 467 ensureValidStreamType(streamType); 468 return (mStreamStates[streamType].mIndex + 5) / 10; 469 } 470 471 /** @see AudioManager#getStreamMaxVolume(int) */ 472 public int getStreamMaxVolume(int streamType) { 473 ensureValidStreamType(streamType); 474 return (mStreamStates[streamType].getMaxIndex() + 5) / 10; 475 } 476 477 /** @see AudioManager#getRingerMode() */ 478 public int getRingerMode() { 479 return mRingerMode; 480 } 481 482 /** @see AudioManager#setRingerMode(int) */ 483 public void setRingerMode(int ringerMode) { 484 synchronized (mSettingsLock) { 485 if (ringerMode != mRingerMode) { 486 setRingerModeInt(ringerMode, true); 487 // Send sticky broadcast 488 broadcastRingerMode(); 489 } 490 } 491 } 492 493 private void setRingerModeInt(int ringerMode, boolean persist) { 494 mRingerMode = ringerMode; 495 496 // Adjust volumes via posting message 497 int numStreamTypes = AudioSystem.getNumStreamTypes(); 498 if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) { 499 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 500 if (!isStreamAffectedByRingerMode(streamType)) continue; 501 // Bring back last audible volume 502 setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex, 503 false, false); 504 } 505 } else { 506 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 507 if (isStreamAffectedByRingerMode(streamType)) { 508 // Either silent or vibrate, either way volume is 0 509 setStreamVolumeInt(streamType, 0, false, false); 510 } else { 511 // restore stream volume in the case the stream changed from affected 512 // to non affected by ringer mode. Does not arm to do it for streams that 513 // are not affected as well. 514 setStreamVolumeInt(streamType, mStreamStates[streamType].mLastAudibleIndex, 515 false, false); 516 } 517 } 518 } 519 520 // Post a persist ringer mode msg 521 if (persist) { 522 sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG, 523 SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY); 524 } 525 } 526 527 /** @see AudioManager#shouldVibrate(int) */ 528 public boolean shouldVibrate(int vibrateType) { 529 530 switch (getVibrateSetting(vibrateType)) { 531 532 case AudioManager.VIBRATE_SETTING_ON: 533 return mRingerMode != AudioManager.RINGER_MODE_SILENT; 534 535 case AudioManager.VIBRATE_SETTING_ONLY_SILENT: 536 return mRingerMode == AudioManager.RINGER_MODE_VIBRATE; 537 538 case AudioManager.VIBRATE_SETTING_OFF: 539 // Phone ringer should always vibrate in vibrate mode 540 if (vibrateType == AudioManager.VIBRATE_TYPE_RINGER) { 541 return mRingerMode == AudioManager.RINGER_MODE_VIBRATE; 542 } 543 544 default: 545 return false; 546 } 547 } 548 549 /** @see AudioManager#getVibrateSetting(int) */ 550 public int getVibrateSetting(int vibrateType) { 551 return (mVibrateSetting >> (vibrateType * 2)) & 3; 552 } 553 554 /** @see AudioManager#setVibrateSetting(int, int) */ 555 public void setVibrateSetting(int vibrateType, int vibrateSetting) { 556 557 mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting); 558 559 // Broadcast change 560 broadcastVibrateSetting(vibrateType); 561 562 // Post message to set ringer mode (it in turn will post a message 563 // to persist) 564 sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0, 565 null, 0); 566 } 567 568 /** 569 * @see #setVibrateSetting(int, int) 570 */ 571 public static int getValueForVibrateSetting(int existingValue, int vibrateType, 572 int vibrateSetting) { 573 574 // First clear the existing setting. Each vibrate type has two bits in 575 // the value. Note '3' is '11' in binary. 576 existingValue &= ~(3 << (vibrateType * 2)); 577 578 // Set into the old value 579 existingValue |= (vibrateSetting & 3) << (vibrateType * 2); 580 581 return existingValue; 582 } 583 584 /** @see AudioManager#setMode(int) */ 585 public void setMode(int mode) { 586 if (!checkAudioSettingsPermission("setMode()")) { 587 return; 588 } 589 590 if (mode < AudioSystem.MODE_CURRENT || mode > AudioSystem.MODE_IN_CALL) { 591 return; 592 } 593 594 synchronized (mSettingsLock) { 595 if (mode == AudioSystem.MODE_CURRENT) { 596 mode = mMode; 597 } 598 if (mode != mMode) { 599 if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) { 600 mMode = mode; 601 } 602 } 603 int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); 604 int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex; 605 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, true); 606 } 607 } 608 609 /** @see AudioManager#getMode() */ 610 public int getMode() { 611 return mMode; 612 } 613 614 /** @see AudioManager#playSoundEffect(int) */ 615 public void playSoundEffect(int effectType) { 616 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, 617 effectType, -1, null, 0); 618 } 619 620 /** @see AudioManager#playSoundEffect(int, float) */ 621 public void playSoundEffectVolume(int effectType, float volume) { 622 loadSoundEffects(); 623 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP, 624 effectType, (int) (volume * 1000), null, 0); 625 } 626 627 /** 628 * Loads samples into the soundpool. 629 * This method must be called at when sound effects are enabled 630 */ 631 public boolean loadSoundEffects() { 632 synchronized (mSoundEffectsLock) { 633 if (mSoundPool != null) { 634 return true; 635 } 636 mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0); 637 if (mSoundPool == null) { 638 return false; 639 } 640 /* 641 * poolId table: The value -1 in this table indicates that corresponding 642 * file (same index in SOUND_EFFECT_FILES[] has not been loaded. 643 * Once loaded, the value in poolId is the sample ID and the same 644 * sample can be reused for another effect using the same file. 645 */ 646 int[] poolId = new int[SOUND_EFFECT_FILES.length]; 647 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { 648 poolId[fileIdx] = -1; 649 } 650 /* 651 * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded. 652 * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0: 653 * this indicates we have a valid sample loaded for this effect. 654 */ 655 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { 656 // Do not load sample if this effect uses the MediaPlayer 657 if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) { 658 continue; 659 } 660 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) { 661 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]]; 662 int sampleId = mSoundPool.load(filePath, 0); 663 SOUND_EFFECT_FILES_MAP[effect][1] = sampleId; 664 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId; 665 if (sampleId <= 0) { 666 Log.w(TAG, "Soundpool could not load file: "+filePath); 667 } 668 } else { 669 SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]]; 670 } 671 } 672 } 673 674 return true; 675 } 676 677 /** 678 * Unloads samples from the sound pool. 679 * This method can be called to free some memory when 680 * sound effects are disabled. 681 */ 682 public void unloadSoundEffects() { 683 synchronized (mSoundEffectsLock) { 684 if (mSoundPool == null) { 685 return; 686 } 687 int[] poolId = new int[SOUND_EFFECT_FILES.length]; 688 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { 689 poolId[fileIdx] = 0; 690 } 691 692 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { 693 if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) { 694 continue; 695 } 696 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) { 697 mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]); 698 SOUND_EFFECT_FILES_MAP[effect][1] = -1; 699 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1; 700 } 701 } 702 mSoundPool = null; 703 } 704 } 705 706 /** @see AudioManager#reloadAudioSettings() */ 707 public void reloadAudioSettings() { 708 // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings 709 readPersistedSettings(); 710 711 // restore volume settings 712 int numStreamTypes = AudioSystem.getNumStreamTypes(); 713 for (int streamType = 0; streamType < numStreamTypes; streamType++) { 714 VolumeStreamState streamState = mStreamStates[streamType]; 715 716 String settingName = System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[streamType]]; 717 String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; 718 int index = Settings.System.getInt(mContentResolver, 719 settingName, 720 AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 721 if (STREAM_VOLUME_ALIAS[streamType] != streamType) { 722 index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType); 723 } else { 724 index *= 10; 725 } 726 streamState.mIndex = streamState.getValidIndex(index); 727 728 index = (index + 5) / 10; 729 index = Settings.System.getInt(mContentResolver, 730 lastAudibleSettingName, 731 (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 732 if (STREAM_VOLUME_ALIAS[streamType] != streamType) { 733 index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType); 734 } else { 735 index *= 10; 736 } 737 streamState.mLastAudibleIndex = streamState.getValidIndex(index); 738 739 // unmute stream that whas muted but is not affect by mute anymore 740 if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) { 741 int size = streamState.mDeathHandlers.size(); 742 for (int i = 0; i < size; i++) { 743 streamState.mDeathHandlers.get(i).mMuteCount = 1; 744 streamState.mDeathHandlers.get(i).mute(false); 745 } 746 } 747 // apply stream volume 748 if (streamState.muteCount() == 0) { 749 setStreamVolumeIndex(streamType, streamState.mIndex); 750 } 751 } 752 753 // apply new ringer mode 754 setRingerModeInt(getRingerMode(), false); 755 } 756 757 /** @see AudioManager#setSpeakerphoneOn() */ 758 public void setSpeakerphoneOn(boolean on){ 759 if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) { 760 return; 761 } 762 if (on) { 763 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_SPEAKER); 764 mForcedUseForComm = AudioSystem.FORCE_SPEAKER; 765 } else { 766 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE); 767 mForcedUseForComm = AudioSystem.FORCE_NONE; 768 } 769 } 770 771 /** @see AudioManager#isSpeakerphoneOn() */ 772 public boolean isSpeakerphoneOn() { 773 if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER) { 774 return true; 775 } else { 776 return false; 777 } 778 } 779 780 /** @see AudioManager#setBluetoothScoOn() */ 781 public void setBluetoothScoOn(boolean on){ 782 if (!checkAudioSettingsPermission("setBluetoothScoOn()")) { 783 return; 784 } 785 if (on) { 786 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_BT_SCO); 787 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_BT_SCO); 788 mForcedUseForComm = AudioSystem.FORCE_BT_SCO; 789 } else { 790 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE); 791 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE); 792 mForcedUseForComm = AudioSystem.FORCE_NONE; 793 } 794 } 795 796 /** @see AudioManager#isBluetoothScoOn() */ 797 public boolean isBluetoothScoOn() { 798 if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) { 799 return true; 800 } else { 801 return false; 802 } 803 } 804 805 /////////////////////////////////////////////////////////////////////////// 806 // Internal methods 807 /////////////////////////////////////////////////////////////////////////// 808 809 /** 810 * Checks if the adjustment should change ringer mode instead of just 811 * adjusting volume. If so, this will set the proper ringer mode and volume 812 * indices on the stream states. 813 */ 814 private boolean checkForRingerModeChange(int oldIndex, int direction) { 815 boolean adjustVolumeIndex = true; 816 int newRingerMode = mRingerMode; 817 818 if (mRingerMode == AudioManager.RINGER_MODE_NORMAL && (oldIndex + 5) / 10 == 1 819 && direction == AudioManager.ADJUST_LOWER) { 820 newRingerMode = AudioManager.RINGER_MODE_VIBRATE; 821 } else if (mRingerMode == AudioManager.RINGER_MODE_VIBRATE) { 822 if (direction == AudioManager.ADJUST_RAISE) { 823 newRingerMode = AudioManager.RINGER_MODE_NORMAL; 824 } else if (direction == AudioManager.ADJUST_LOWER) { 825 newRingerMode = AudioManager.RINGER_MODE_SILENT; 826 } 827 } else if (direction == AudioManager.ADJUST_RAISE 828 && mRingerMode == AudioManager.RINGER_MODE_SILENT) { 829 newRingerMode = AudioManager.RINGER_MODE_VIBRATE; 830 } 831 832 if (newRingerMode != mRingerMode) { 833 setRingerMode(newRingerMode); 834 835 /* 836 * If we are changing ringer modes, do not increment/decrement the 837 * volume index. Instead, the handler for the message above will 838 * take care of changing the index. 839 */ 840 adjustVolumeIndex = false; 841 } 842 843 return adjustVolumeIndex; 844 } 845 846 public boolean isStreamAffectedByRingerMode(int streamType) { 847 return (mRingerModeAffectedStreams & (1 << streamType)) != 0; 848 } 849 850 public boolean isStreamAffectedByMute(int streamType) { 851 return (mMuteAffectedStreams & (1 << streamType)) != 0; 852 } 853 854 private void ensureValidDirection(int direction) { 855 if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) { 856 throw new IllegalArgumentException("Bad direction " + direction); 857 } 858 } 859 860 private void ensureValidStreamType(int streamType) { 861 if (streamType < 0 || streamType >= mStreamStates.length) { 862 throw new IllegalArgumentException("Bad stream type " + streamType); 863 } 864 } 865 866 private int getActiveStreamType(int suggestedStreamType) { 867 boolean isOffhook = false; 868 try { 869 ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); 870 if (phone != null) isOffhook = phone.isOffhook(); 871 } catch (RemoteException e) { 872 Log.w(TAG, "Couldn't connect to phone service", e); 873 } 874 875 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) { 876 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO..."); 877 return AudioSystem.STREAM_BLUETOOTH_SCO; 878 } else if (isOffhook) { 879 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL..."); 880 return AudioSystem.STREAM_VOICE_CALL; 881 } else if (AudioSystem.isMusicActive()) { 882 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC..."); 883 return AudioSystem.STREAM_MUSIC; 884 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) { 885 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING..."); 886 return AudioSystem.STREAM_RING; 887 } else { 888 // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType); 889 return suggestedStreamType; 890 } 891 } 892 893 private void broadcastRingerMode() { 894 // Send sticky broadcast 895 Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION); 896 broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode); 897 broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT 898 | Intent.FLAG_RECEIVER_REPLACE_PENDING); 899 long origCallerIdentityToken = Binder.clearCallingIdentity(); 900 mContext.sendStickyBroadcast(broadcast); 901 Binder.restoreCallingIdentity(origCallerIdentityToken); 902 } 903 904 private void broadcastVibrateSetting(int vibrateType) { 905 // Send broadcast 906 if (ActivityManagerNative.isSystemReady()) { 907 Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION); 908 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType); 909 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType)); 910 mContext.sendBroadcast(broadcast); 911 } 912 } 913 914 // Message helper methods 915 private static int getMsg(int baseMsg, int streamType) { 916 return (baseMsg & 0xffff) | streamType << 16; 917 } 918 919 private static int getMsgBase(int msg) { 920 return msg & 0xffff; 921 } 922 923 private static void sendMsg(Handler handler, int baseMsg, int streamType, 924 int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) { 925 int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType); 926 927 if (existingMsgPolicy == SENDMSG_REPLACE) { 928 handler.removeMessages(msg); 929 } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { 930 return; 931 } 932 933 handler 934 .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay); 935 } 936 937 boolean checkAudioSettingsPermission(String method) { 938 if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS") 939 == PackageManager.PERMISSION_GRANTED) { 940 return true; 941 } 942 String msg = "Audio Settings Permission Denial: " + method + " from pid=" 943 + Binder.getCallingPid() 944 + ", uid=" + Binder.getCallingUid(); 945 Log.w(TAG, msg); 946 return false; 947 } 948 949 950 /////////////////////////////////////////////////////////////////////////// 951 // Inner classes 952 /////////////////////////////////////////////////////////////////////////// 953 954 public class VolumeStreamState { 955 private final int mStreamType; 956 957 private String mVolumeIndexSettingName; 958 private String mLastAudibleVolumeIndexSettingName; 959 private int mIndexMax; 960 private int mIndex; 961 private int mLastAudibleIndex; 962 private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death 963 964 private VolumeStreamState(String settingName, int streamType) { 965 966 setVolumeIndexSettingName(settingName); 967 968 mStreamType = streamType; 969 970 final ContentResolver cr = mContentResolver; 971 mIndexMax = MAX_STREAM_VOLUME[streamType]; 972 mIndex = Settings.System.getInt(cr, 973 mVolumeIndexSettingName, 974 AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 975 mLastAudibleIndex = Settings.System.getInt(cr, 976 mLastAudibleVolumeIndexSettingName, 977 (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]); 978 AudioSystem.initStreamVolume(streamType, 0, mIndexMax); 979 mIndexMax *= 10; 980 mIndex = getValidIndex(10 * mIndex); 981 mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex); 982 setStreamVolumeIndex(streamType, mIndex); 983 mDeathHandlers = new ArrayList<VolumeDeathHandler>(); 984 } 985 986 public void setVolumeIndexSettingName(String settingName) { 987 mVolumeIndexSettingName = settingName; 988 mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; 989 } 990 991 public boolean adjustIndex(int deltaIndex) { 992 return setIndex(mIndex + deltaIndex * 10, true); 993 } 994 995 public boolean setIndex(int index, boolean lastAudible) { 996 int oldIndex = mIndex; 997 mIndex = getValidIndex(index); 998 999 if (oldIndex != mIndex) { 1000 if (lastAudible) { 1001 mLastAudibleIndex = mIndex; 1002 } 1003 // Apply change to all streams using this one as alias 1004 int numStreamTypes = AudioSystem.getNumStreamTypes(); 1005 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 1006 if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) { 1007 mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible); 1008 } 1009 } 1010 return true; 1011 } else { 1012 return false; 1013 } 1014 } 1015 1016 public int getMaxIndex() { 1017 return mIndexMax; 1018 } 1019 1020 public void mute(IBinder cb, boolean state) { 1021 VolumeDeathHandler handler = getDeathHandler(cb, state); 1022 if (handler == null) { 1023 Log.e(TAG, "Could not get client death handler for stream: "+mStreamType); 1024 return; 1025 } 1026 handler.mute(state); 1027 } 1028 1029 private int getValidIndex(int index) { 1030 if (index < 0) { 1031 return 0; 1032 } else if (index > mIndexMax) { 1033 return mIndexMax; 1034 } 1035 1036 return index; 1037 } 1038 1039 private class VolumeDeathHandler implements IBinder.DeathRecipient { 1040 private IBinder mICallback; // To be notified of client's death 1041 private int mMuteCount; // Number of active mutes for this client 1042 1043 VolumeDeathHandler(IBinder cb) { 1044 mICallback = cb; 1045 } 1046 1047 public void mute(boolean state) { 1048 synchronized(mDeathHandlers) { 1049 if (state) { 1050 if (mMuteCount == 0) { 1051 // Register for client death notification 1052 try { 1053 mICallback.linkToDeath(this, 0); 1054 mDeathHandlers.add(this); 1055 // If the stream is not yet muted by any client, set lvel to 0 1056 if (muteCount() == 0) { 1057 setIndex(0, false); 1058 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0, 1059 VolumeStreamState.this, 0); 1060 } 1061 } catch (RemoteException e) { 1062 // Client has died! 1063 binderDied(); 1064 mDeathHandlers.notify(); 1065 return; 1066 } 1067 } else { 1068 Log.w(TAG, "stream: "+mStreamType+" was already muted by this client"); 1069 } 1070 mMuteCount++; 1071 } else { 1072 if (mMuteCount == 0) { 1073 Log.e(TAG, "unexpected unmute for stream: "+mStreamType); 1074 } else { 1075 mMuteCount--; 1076 if (mMuteCount == 0) { 1077 // Unregistr from client death notification 1078 mDeathHandlers.remove(this); 1079 mICallback.unlinkToDeath(this, 0); 1080 if (muteCount() == 0) { 1081 // If the stream is not mut any more, restore it's volume if 1082 // ringer mode allows it 1083 if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) { 1084 setIndex(mLastAudibleIndex, false); 1085 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0, 1086 VolumeStreamState.this, 0); 1087 } 1088 } 1089 } 1090 } 1091 } 1092 mDeathHandlers.notify(); 1093 } 1094 } 1095 1096 public void binderDied() { 1097 Log.w(TAG, "Volume service client died for stream: "+mStreamType); 1098 if (mMuteCount != 0) { 1099 // Reset all active mute requests from this client. 1100 mMuteCount = 1; 1101 mute(false); 1102 } 1103 } 1104 } 1105 1106 private int muteCount() { 1107 int count = 0; 1108 int size = mDeathHandlers.size(); 1109 for (int i = 0; i < size; i++) { 1110 count += mDeathHandlers.get(i).mMuteCount; 1111 } 1112 return count; 1113 } 1114 1115 private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) { 1116 synchronized(mDeathHandlers) { 1117 VolumeDeathHandler handler; 1118 int size = mDeathHandlers.size(); 1119 for (int i = 0; i < size; i++) { 1120 handler = mDeathHandlers.get(i); 1121 if (cb.equals(handler.mICallback)) { 1122 return handler; 1123 } 1124 } 1125 // If this is the first mute request for this client, create a new 1126 // client death handler. Otherwise, it is an out of sequence unmute request. 1127 if (state) { 1128 handler = new VolumeDeathHandler(cb); 1129 } else { 1130 Log.w(TAG, "stream was not muted by this client"); 1131 handler = null; 1132 } 1133 return handler; 1134 } 1135 } 1136 } 1137 1138 /** Thread that handles native AudioSystem control. */ 1139 private class AudioSystemThread extends Thread { 1140 AudioSystemThread() { 1141 super("AudioService"); 1142 } 1143 1144 @Override 1145 public void run() { 1146 // Set this thread up so the handler will work on it 1147 Looper.prepare(); 1148 1149 synchronized(AudioService.this) { 1150 mAudioHandler = new AudioHandler(); 1151 1152 // Notify that the handler has been created 1153 AudioService.this.notify(); 1154 } 1155 1156 // Listen for volume change requests that are set by VolumePanel 1157 Looper.loop(); 1158 } 1159 } 1160 1161 /** Handles internal volume messages in separate volume thread. */ 1162 private class AudioHandler extends Handler { 1163 1164 private void setSystemVolume(VolumeStreamState streamState) { 1165 1166 // Adjust volume 1167 setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex); 1168 1169 // Apply change to all streams using this one as alias 1170 int numStreamTypes = AudioSystem.getNumStreamTypes(); 1171 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 1172 if (streamType != streamState.mStreamType && 1173 STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) { 1174 setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex); 1175 } 1176 } 1177 1178 // Post a persist volume msg 1179 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType, 1180 SENDMSG_REPLACE, 0, 0, streamState, PERSIST_DELAY); 1181 } 1182 1183 private void persistVolume(VolumeStreamState streamState) { 1184 System.putInt(mContentResolver, streamState.mVolumeIndexSettingName, 1185 (streamState.mIndex + 5)/ 10); 1186 System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName, 1187 (streamState.mLastAudibleIndex + 5) / 10); 1188 } 1189 1190 private void persistRingerMode() { 1191 System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode); 1192 } 1193 1194 private void persistVibrateSetting() { 1195 System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting); 1196 } 1197 1198 private void playSoundEffect(int effectType, int volume) { 1199 synchronized (mSoundEffectsLock) { 1200 if (mSoundPool == null) { 1201 return; 1202 } 1203 float volFloat; 1204 // use STREAM_MUSIC volume attenuated by 3 dB if volume is not specified by caller 1205 if (volume < 0) { 1206 // Same linear to log conversion as in native AudioSystem::linearToLog() (AudioSystem.cpp) 1207 float dBPerStep = (float)((0.5 * 100) / MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]); 1208 int musicVolIndex = (mStreamStates[AudioSystem.STREAM_MUSIC].mIndex + 5) / 10; 1209 float musicVoldB = dBPerStep * (musicVolIndex - MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]); 1210 volFloat = (float)Math.pow(10, (musicVoldB - 3)/20); 1211 } else { 1212 volFloat = (float) volume / 1000.0f; 1213 } 1214 1215 if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) { 1216 mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f); 1217 } else { 1218 MediaPlayer mediaPlayer = new MediaPlayer(); 1219 if (mediaPlayer != null) { 1220 try { 1221 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]]; 1222 mediaPlayer.setDataSource(filePath); 1223 mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM); 1224 mediaPlayer.prepare(); 1225 mediaPlayer.setVolume(volFloat, volFloat); 1226 mediaPlayer.setOnCompletionListener(new OnCompletionListener() { 1227 public void onCompletion(MediaPlayer mp) { 1228 cleanupPlayer(mp); 1229 } 1230 }); 1231 mediaPlayer.setOnErrorListener(new OnErrorListener() { 1232 public boolean onError(MediaPlayer mp, int what, int extra) { 1233 cleanupPlayer(mp); 1234 return true; 1235 } 1236 }); 1237 mediaPlayer.start(); 1238 } catch (IOException ex) { 1239 Log.w(TAG, "MediaPlayer IOException: "+ex); 1240 } catch (IllegalArgumentException ex) { 1241 Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex); 1242 } catch (IllegalStateException ex) { 1243 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); 1244 } 1245 } 1246 } 1247 } 1248 } 1249 1250 private void cleanupPlayer(MediaPlayer mp) { 1251 if (mp != null) { 1252 try { 1253 mp.stop(); 1254 mp.release(); 1255 } catch (IllegalStateException ex) { 1256 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); 1257 } 1258 } 1259 } 1260 1261 @Override 1262 public void handleMessage(Message msg) { 1263 int baseMsgWhat = getMsgBase(msg.what); 1264 1265 switch (baseMsgWhat) { 1266 1267 case MSG_SET_SYSTEM_VOLUME: 1268 setSystemVolume((VolumeStreamState) msg.obj); 1269 break; 1270 1271 case MSG_PERSIST_VOLUME: 1272 persistVolume((VolumeStreamState) msg.obj); 1273 break; 1274 1275 case MSG_PERSIST_RINGER_MODE: 1276 persistRingerMode(); 1277 break; 1278 1279 case MSG_PERSIST_VIBRATE_SETTING: 1280 persistVibrateSetting(); 1281 break; 1282 1283 case MSG_MEDIA_SERVER_DIED: 1284 // Force creation of new IAudioflinger interface 1285 if (!mMediaServerOk) { 1286 Log.e(TAG, "Media server died."); 1287 AudioSystem.isMusicActive(); 1288 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0, 1289 null, 500); 1290 } 1291 break; 1292 1293 case MSG_MEDIA_SERVER_STARTED: 1294 Log.e(TAG, "Media server started."); 1295 // Restore device connection states 1296 Set set = mConnectedDevices.entrySet(); 1297 Iterator i = set.iterator(); 1298 while(i.hasNext()){ 1299 Map.Entry device = (Map.Entry)i.next(); 1300 AudioSystem.setDeviceConnectionState(((Integer)device.getKey()).intValue(), 1301 AudioSystem.DEVICE_STATE_AVAILABLE, 1302 (String)device.getValue()); 1303 } 1304 1305 // Restore call state 1306 AudioSystem.setPhoneState(mMode); 1307 1308 // Restore forced usage for communcations and record 1309 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm); 1310 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm); 1311 1312 // Restore stream volumes 1313 int numStreamTypes = AudioSystem.getNumStreamTypes(); 1314 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { 1315 int index; 1316 VolumeStreamState streamState = mStreamStates[streamType]; 1317 AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10); 1318 if (streamState.muteCount() == 0) { 1319 index = streamState.mIndex; 1320 } else { 1321 index = 0; 1322 } 1323 setStreamVolumeIndex(streamType, index); 1324 } 1325 1326 // Restore ringer mode 1327 setRingerModeInt(getRingerMode(), false); 1328 break; 1329 1330 case MSG_PLAY_SOUND_EFFECT: 1331 playSoundEffect(msg.arg1, msg.arg2); 1332 break; 1333 } 1334 } 1335 } 1336 1337 private class SettingsObserver extends ContentObserver { 1338 1339 SettingsObserver() { 1340 super(new Handler()); 1341 mContentResolver.registerContentObserver(Settings.System.getUriFor( 1342 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this); 1343 mContentResolver.registerContentObserver(Settings.System.getUriFor( 1344 Settings.System.NOTIFICATIONS_USE_RING_VOLUME), false, this); 1345 } 1346 1347 @Override 1348 public void onChange(boolean selfChange) { 1349 super.onChange(selfChange); 1350 synchronized (mSettingsLock) { 1351 int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver, 1352 Settings.System.MODE_RINGER_STREAMS_AFFECTED, 1353 0); 1354 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) { 1355 /* 1356 * Ensure all stream types that should be affected by ringer mode 1357 * are in the proper state. 1358 */ 1359 mRingerModeAffectedStreams = ringerModeAffectedStreams; 1360 setRingerModeInt(getRingerMode(), false); 1361 } 1362 1363 int notificationsUseRingVolume = Settings.System.getInt(mContentResolver, 1364 Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1365 1); 1366 if (notificationsUseRingVolume != mNotificationsUseRingVolume) { 1367 mNotificationsUseRingVolume = notificationsUseRingVolume; 1368 if (mNotificationsUseRingVolume == 1) { 1369 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING; 1370 mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName( 1371 System.VOLUME_SETTINGS[AudioSystem.STREAM_RING]); 1372 } else { 1373 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION; 1374 mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName( 1375 System.VOLUME_SETTINGS[AudioSystem.STREAM_NOTIFICATION]); 1376 // Persist notification volume volume as it was not persisted while aliased to ring volume 1377 // and persist with no delay as there might be registered observers of the persisted 1378 // notification volume. 1379 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, AudioSystem.STREAM_NOTIFICATION, 1380 SENDMSG_REPLACE, 0, 0, mStreamStates[AudioSystem.STREAM_NOTIFICATION], 0); 1381 } 1382 } 1383 } 1384 } 1385 } 1386 1387 /** 1388 * Receiver for misc intent broadcasts the Phone app cares about. 1389 */ 1390 private class AudioServiceBroadcastReceiver extends BroadcastReceiver { 1391 @Override 1392 public void onReceive(Context context, Intent intent) { 1393 String action = intent.getAction(); 1394 1395 if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) { 1396 int state = intent.getIntExtra(BluetoothA2dp.EXTRA_SINK_STATE, 1397 BluetoothA2dp.STATE_DISCONNECTED); 1398 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 1399 String address = btDevice.getAddress(); 1400 boolean isConnected = (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) && 1401 ((String)mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)).equals(address)); 1402 1403 if (isConnected && 1404 state != BluetoothA2dp.STATE_CONNECTED && state != BluetoothA2dp.STATE_PLAYING) { 1405 if (address.equals(sBtDockAddress)) { 1406 Log.v(TAG, "Recognized undocking from BT dock"); 1407 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, AudioSystem.FORCE_NONE); 1408 } 1409 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 1410 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1411 address); 1412 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP); 1413 } else if (!isConnected && 1414 (state == BluetoothA2dp.STATE_CONNECTED || 1415 state == BluetoothA2dp.STATE_PLAYING)) { 1416 if (btDevice.isBluetoothDock()) { 1417 Log.v(TAG, "Recognized docking to BT dock"); 1418 sBtDockAddress = address; 1419 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, AudioSystem.FORCE_BT_DOCK); 1420 } 1421 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, 1422 AudioSystem.DEVICE_STATE_AVAILABLE, 1423 address); 1424 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP), 1425 address); 1426 } 1427 } else if (action.equals(BluetoothHeadset.ACTION_STATE_CHANGED)) { 1428 int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, 1429 BluetoothHeadset.STATE_ERROR); 1430 int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO; 1431 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 1432 String address = null; 1433 if (btDevice != null) { 1434 address = btDevice.getAddress(); 1435 BluetoothClass btClass = btDevice.getBluetoothClass(); 1436 if (btClass != null) { 1437 switch (btClass.getDeviceClass()) { 1438 case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET: 1439 case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE: 1440 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET; 1441 break; 1442 case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO: 1443 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT; 1444 break; 1445 } 1446 } 1447 } 1448 1449 boolean isConnected = (mConnectedDevices.containsKey(device) && 1450 ((String)mConnectedDevices.get(device)).equals(address)); 1451 1452 if (isConnected && state != BluetoothHeadset.STATE_CONNECTED) { 1453 AudioSystem.setDeviceConnectionState(device, 1454 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1455 address); 1456 mConnectedDevices.remove(device); 1457 } else if (!isConnected && state == BluetoothHeadset.STATE_CONNECTED) { 1458 AudioSystem.setDeviceConnectionState(device, 1459 AudioSystem.DEVICE_STATE_AVAILABLE, 1460 address); 1461 mConnectedDevices.put(new Integer(device), address); 1462 } 1463 } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { 1464 int state = intent.getIntExtra("state", 0); 1465 int microphone = intent.getIntExtra("microphone", 0); 1466 1467 if (microphone != 0) { 1468 boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET); 1469 if (state == 0 && isConnected) { 1470 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET, 1471 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1472 ""); 1473 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET); 1474 } else if (state == 1 && !isConnected) { 1475 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET, 1476 AudioSystem.DEVICE_STATE_AVAILABLE, 1477 ""); 1478 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), ""); 1479 } 1480 } else { 1481 boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE); 1482 if (state == 0 && isConnected) { 1483 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, 1484 AudioSystem.DEVICE_STATE_UNAVAILABLE, 1485 ""); 1486 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE); 1487 } else if (state == 1 && !isConnected) { 1488 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE, 1489 AudioSystem.DEVICE_STATE_AVAILABLE, 1490 ""); 1491 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), ""); 1492 } 1493 } 1494 } 1495 } 1496 } 1497} 1498