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