blob: 23f34d28c80f71b7c3e1c753cb9f5c9fbe6c4903 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -070020import android.bluetooth.BluetoothA2dp;
21import android.bluetooth.BluetoothAdapter;
22import android.bluetooth.BluetoothClass;
23import android.bluetooth.BluetoothDevice;
24import android.bluetooth.BluetoothHeadset;
25import android.bluetooth.BluetoothProfile;
Nick Pellybd022f42009-08-14 18:33:38 -070026import android.content.BroadcastReceiver;
Jean-Michel Trivid327f212010-03-16 21:44:33 -070027import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
Eric Laurenta553c252009-07-17 12:17:14 -070031import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.pm.PackageManager;
Jason Parekhb1096152009-03-24 17:48:25 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.media.MediaPlayer.OnCompletionListener;
35import android.media.MediaPlayer.OnErrorListener;
36import android.os.Binder;
37import android.os.Environment;
38import android.os.Handler;
39import android.os.IBinder;
40import android.os.Looper;
41import android.os.Message;
42import android.os.RemoteException;
43import android.os.ServiceManager;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -070044import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.provider.Settings;
46import android.provider.Settings.System;
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -070047import android.telephony.PhoneStateListener;
48import android.telephony.TelephonyManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.util.Log;
Jean-Michel Trivid327f212010-03-16 21:44:33 -070050import android.view.KeyEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.view.VolumePanel;
52
53import com.android.internal.telephony.ITelephony;
54
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -080055import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.io.IOException;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -080057import java.io.PrintWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.ArrayList;
Eric Laurentc42ac9d2009-07-29 08:53:03 -070059import java.util.HashMap;
60import java.util.Iterator;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070061import java.util.List;
Eric Laurentc42ac9d2009-07-29 08:53:03 -070062import java.util.Map;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -070063import java.util.NoSuchElementException;
Eric Laurentc42ac9d2009-07-29 08:53:03 -070064import java.util.Set;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -080065import java.util.Stack;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67/**
68 * The implementation of the volume manager service.
69 * <p>
70 * This implementation focuses on delivering a responsive UI. Most methods are
71 * asynchronous to external calls. For example, the task of setting a volume
72 * will update our internal state, but in a separate thread will set the system
73 * volume and later persist to the database. Similarly, setting the ringer mode
74 * will update the state and broadcast a change and in a separate thread later
75 * persist the ringer mode.
76 *
77 * @hide
78 */
79public class AudioService extends IAudioService.Stub {
80
81 private static final String TAG = "AudioService";
82
83 /** How long to delay before persisting a change in volume/ringer mode. */
84 private static final int PERSIST_DELAY = 3000;
85
86 private Context mContext;
87 private ContentResolver mContentResolver;
88
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -080089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 /** The UI */
91 private VolumePanel mVolumePanel;
92
93 // sendMsg() flags
94 /** Used when a message should be shared across all stream types. */
95 private static final int SHARED_MSG = -1;
96 /** If the msg is already queued, replace it with this one. */
97 private static final int SENDMSG_REPLACE = 0;
98 /** If the msg is already queued, ignore this one and leave the old. */
99 private static final int SENDMSG_NOOP = 1;
100 /** If the msg is already queued, queue this one and leave the old. */
101 private static final int SENDMSG_QUEUE = 2;
102
103 // AudioHandler message.whats
104 private static final int MSG_SET_SYSTEM_VOLUME = 0;
105 private static final int MSG_PERSIST_VOLUME = 1;
106 private static final int MSG_PERSIST_RINGER_MODE = 3;
107 private static final int MSG_PERSIST_VIBRATE_SETTING = 4;
108 private static final int MSG_MEDIA_SERVER_DIED = 5;
109 private static final int MSG_MEDIA_SERVER_STARTED = 6;
110 private static final int MSG_PLAY_SOUND_EFFECT = 7;
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -0700111 private static final int MSG_BTA2DP_DOCK_TIMEOUT = 8;
112
113 private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
115 /** @see AudioSystemThread */
116 private AudioSystemThread mAudioSystemThread;
117 /** @see AudioHandler */
118 private AudioHandler mAudioHandler;
119 /** @see VolumeStreamState */
120 private VolumeStreamState[] mStreamStates;
Jason Parekhb1096152009-03-24 17:48:25 -0700121 private SettingsObserver mSettingsObserver;
Eric Laurenta553c252009-07-17 12:17:14 -0700122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private int mMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 private Object mSettingsLock = new Object();
125 private boolean mMediaServerOk;
126
127 private SoundPool mSoundPool;
128 private Object mSoundEffectsLock = new Object();
129 private static final int NUM_SOUNDPOOL_CHANNELS = 4;
130 private static final int SOUND_EFFECT_VOLUME = 1000;
131
132 /* Sound effect file names */
133 private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/";
134 private static final String[] SOUND_EFFECT_FILES = new String[] {
135 "Effect_Tick.ogg",
136 "KeypressStandard.ogg",
137 "KeypressSpacebar.ogg",
138 "KeypressDelete.ogg",
139 "KeypressReturn.ogg"
140 };
141
142 /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to
143 * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect
144 * uses soundpool (second column) */
145 private int[][] SOUND_EFFECT_FILES_MAP = new int[][] {
146 {0, -1}, // FX_KEY_CLICK
147 {0, -1}, // FX_FOCUS_NAVIGATION_UP
148 {0, -1}, // FX_FOCUS_NAVIGATION_DOWN
149 {0, -1}, // FX_FOCUS_NAVIGATION_LEFT
150 {0, -1}, // FX_FOCUS_NAVIGATION_RIGHT
151 {1, -1}, // FX_KEYPRESS_STANDARD
152 {2, -1}, // FX_KEYPRESS_SPACEBAR
153 {3, -1}, // FX_FOCUS_DELETE
154 {4, -1} // FX_FOCUS_RETURN
155 };
156
Jared Suttles59820132009-08-13 21:50:52 -0500157 /** @hide Maximum volume index values for audio streams */
158 private int[] MAX_STREAM_VOLUME = new int[] {
Eric Laurent6ee99522009-08-25 06:30:59 -0700159 5, // STREAM_VOICE_CALL
160 7, // STREAM_SYSTEM
161 7, // STREAM_RING
162 15, // STREAM_MUSIC
163 7, // STREAM_ALARM
164 7, // STREAM_NOTIFICATION
165 15, // STREAM_BLUETOOTH_SCO
166 7, // STREAM_SYSTEM_ENFORCED
167 15, // STREAM_DTMF
168 15 // STREAM_TTS
Jared Suttles59820132009-08-13 21:50:52 -0500169 };
Eric Laurenta553c252009-07-17 12:17:14 -0700170 /* STREAM_VOLUME_ALIAS[] indicates for each stream if it uses the volume settings
171 * of another stream: This avoids multiplying the volume settings for hidden
172 * stream types that follow other stream behavior for volume settings
173 * NOTE: do not create loops in aliases! */
174 private int[] STREAM_VOLUME_ALIAS = new int[] {
175 AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL
176 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM
177 AudioSystem.STREAM_RING, // STREAM_RING
178 AudioSystem.STREAM_MUSIC, // STREAM_MUSIC
179 AudioSystem.STREAM_ALARM, // STREAM_ALARM
180 AudioSystem.STREAM_NOTIFICATION, // STREAM_NOTIFICATION
Eric Laurent484d2882009-12-08 09:05:45 -0800181 AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO
Eric Laurenta553c252009-07-17 12:17:14 -0700182 AudioSystem.STREAM_SYSTEM, // STREAM_SYSTEM_ENFORCED
183 AudioSystem.STREAM_VOICE_CALL, // STREAM_DTMF
184 AudioSystem.STREAM_MUSIC // STREAM_TTS
185 };
186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() {
188 public void onError(int error) {
189 switch (error) {
190 case AudioSystem.AUDIO_STATUS_SERVER_DIED:
191 if (mMediaServerOk) {
192 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
193 null, 1500);
Eric Laurent89e74ba2009-09-30 18:26:36 -0700194 mMediaServerOk = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 }
196 break;
197 case AudioSystem.AUDIO_STATUS_OK:
198 if (!mMediaServerOk) {
199 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
200 null, 0);
Eric Laurent89e74ba2009-09-30 18:26:36 -0700201 mMediaServerOk = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 }
203 break;
204 default:
205 break;
206 }
207 }
208 };
209
210 /**
211 * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL},
212 * {@link AudioManager#RINGER_MODE_SILENT}, or
213 * {@link AudioManager#RINGER_MODE_VIBRATE}.
214 */
215 private int mRingerMode;
216
Eric Laurent9bcf4012009-06-12 06:09:28 -0700217 /** @see System#MODE_RINGER_STREAMS_AFFECTED */
218 private int mRingerModeAffectedStreams;
219
Eric Laurent5b4e6542010-03-19 20:02:21 -0700220 // Streams currently muted by ringer mode
221 private int mRingerModeMutedStreams;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 /** @see System#MUTE_STREAMS_AFFECTED */
224 private int mMuteAffectedStreams;
225
226 /**
227 * Has multiple bits per vibrate type to indicate the type's vibrate
228 * setting. See {@link #setVibrateSetting(int, int)}.
229 * <p>
230 * NOTE: This is not the final decision of whether vibrate is on/off for the
231 * type since it depends on the ringer mode. See {@link #shouldVibrate(int)}.
232 */
233 private int mVibrateSetting;
234
Eric Laurenta553c252009-07-17 12:17:14 -0700235 /** @see System#NOTIFICATIONS_USE_RING_VOLUME */
236 private int mNotificationsUseRingVolume;
237
238 // Broadcast receiver for device connections intent broadcasts
239 private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver();
240
Jean-Michel Trivid327f212010-03-16 21:44:33 -0700241 // Broadcast receiver for media button broadcasts (separate from mReceiver to
242 // independently change its priority)
243 private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
244
Jean-Michel Trivie73131a2010-06-14 09:53:30 -0700245 // Used to alter media button redirection when the phone is ringing.
246 private boolean mIsRinging = false;
247
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700248 // Devices currently connected
249 private HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>();
250
251 // Forced device usage for communications
252 private int mForcedUseForComm;
253
Eric Laurent9272b4b2010-01-23 17:12:59 -0800254 // List of binder death handlers for setMode() client processes.
255 // The last process to have called setMode() is at the top of the list.
256 private ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>();
Eric Laurenteb14a782009-12-17 03:12:59 -0800257
Eric Laurent3def1ee2010-03-17 23:26:26 -0700258 // List of clients having issued a SCO start request
259 private ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>();
260
261 // BluetoothHeadset API to control SCO connection
262 private BluetoothHeadset mBluetoothHeadset;
263
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700264 // Bluetooth headset device
265 private BluetoothDevice mBluetoothHeadsetDevice;
Eric Laurent3def1ee2010-03-17 23:26:26 -0700266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 ///////////////////////////////////////////////////////////////////////////
268 // Construction
269 ///////////////////////////////////////////////////////////////////////////
270
271 /** @hide */
272 public AudioService(Context context) {
273 mContext = context;
274 mContentResolver = context.getContentResolver();
Jared Suttles59820132009-08-13 21:50:52 -0500275
276 // Intialized volume
277 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt(
278 "ro.config.vc_call_vol_steps",
279 MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]);
280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 mVolumePanel = new VolumePanel(context, this);
Jason Parekhb1096152009-03-24 17:48:25 -0700282 mSettingsObserver = new SettingsObserver();
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700283 mForcedUseForComm = AudioSystem.FORCE_NONE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 createAudioSystemThread();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 readPersistedSettings();
Eric Laurenta553c252009-07-17 12:17:14 -0700286 createStreamStates();
Eric Laurent9272b4b2010-01-23 17:12:59 -0800287 // Call setMode() to initialize mSetModeDeathHandlers
288 mMode = AudioSystem.MODE_INVALID;
289 setMode(AudioSystem.MODE_NORMAL, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 mMediaServerOk = true;
Eric Laurent3891c4c2010-04-20 09:40:57 -0700291
292 // Call setRingerModeInt() to apply correct mute
293 // state on streams affected by ringer mode.
294 mRingerModeMutedStreams = 0;
295 setRingerModeInt(getRingerMode(), false);
296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 AudioSystem.setErrorCallback(mAudioSystemCallback);
298 loadSoundEffects();
Eric Laurenta553c252009-07-17 12:17:14 -0700299
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700300 mBluetoothHeadsetDevice = null;
301 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
302 if (adapter != null) {
303 adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
304 BluetoothProfile.HEADSET);
305 }
Eric Laurent3def1ee2010-03-17 23:26:26 -0700306
Eric Laurenta553c252009-07-17 12:17:14 -0700307 // Register for device connection intent broadcasts.
308 IntentFilter intentFilter =
309 new IntentFilter(Intent.ACTION_HEADSET_PLUG);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700310 intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
Eric Laurent3def1ee2010-03-17 23:26:26 -0700311 intentFilter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -0700312 intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
313 intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
Eric Laurenta553c252009-07-17 12:17:14 -0700314 context.registerReceiver(mReceiver, intentFilter);
Jared Suttles59820132009-08-13 21:50:52 -0500315
Jean-Michel Trivid327f212010-03-16 21:44:33 -0700316 // Register for media button intent broadcasts.
317 intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
318 intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
319 context.registerReceiver(mMediaButtonReceiver, intentFilter);
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -0700320
321 // Register for phone state monitoring
322 TelephonyManager tmgr = (TelephonyManager)
323 context.getSystemService(Context.TELEPHONY_SERVICE);
324 tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 }
326
327 private void createAudioSystemThread() {
328 mAudioSystemThread = new AudioSystemThread();
329 mAudioSystemThread.start();
330 waitForAudioHandlerCreation();
331 }
332
333 /** Waits for the volume handler to be created by the other thread. */
334 private void waitForAudioHandlerCreation() {
335 synchronized(this) {
336 while (mAudioHandler == null) {
337 try {
338 // Wait for mAudioHandler to be set by the other thread
339 wait();
340 } catch (InterruptedException e) {
341 Log.e(TAG, "Interrupted while waiting on volume handler.");
342 }
343 }
344 }
345 }
346
347 private void createStreamStates() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 int numStreamTypes = AudioSystem.getNumStreamTypes();
349 VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes];
350
351 for (int i = 0; i < numStreamTypes; i++) {
Eric Laurenta553c252009-07-17 12:17:14 -0700352 streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[i]], i);
353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354
Eric Laurenta553c252009-07-17 12:17:14 -0700355 // Correct stream index values for streams with aliases
356 for (int i = 0; i < numStreamTypes; i++) {
357 if (STREAM_VOLUME_ALIAS[i] != i) {
358 int index = rescaleIndex(streams[i].mIndex, STREAM_VOLUME_ALIAS[i], i);
359 streams[i].mIndex = streams[i].getValidIndex(index);
360 setStreamVolumeIndex(i, index);
361 index = rescaleIndex(streams[i].mLastAudibleIndex, STREAM_VOLUME_ALIAS[i], i);
362 streams[i].mLastAudibleIndex = streams[i].getValidIndex(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 }
364 }
365 }
366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 private void readPersistedSettings() {
368 final ContentResolver cr = mContentResolver;
369
370 mRingerMode = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371
372 mVibrateSetting = System.getInt(cr, System.VIBRATE_ON, 0);
373
Eric Laurent9bcf4012009-06-12 06:09:28 -0700374 mRingerModeAffectedStreams = Settings.System.getInt(cr,
375 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
Eric Laurenta553c252009-07-17 12:17:14 -0700376 ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)|
377 (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)));
Eric Laurent9bcf4012009-06-12 06:09:28 -0700378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 mMuteAffectedStreams = System.getInt(cr,
380 System.MUTE_STREAMS_AFFECTED,
381 ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
382
Eric Laurenta553c252009-07-17 12:17:14 -0700383 mNotificationsUseRingVolume = System.getInt(cr,
384 Settings.System.NOTIFICATIONS_USE_RING_VOLUME, 1);
385
386 if (mNotificationsUseRingVolume == 1) {
387 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 // Each stream will read its own persisted settings
390
391 // Broadcast the sticky intent
392 broadcastRingerMode();
393
394 // Broadcast vibrate settings
395 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
396 broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION);
397 }
398
Eric Laurenta553c252009-07-17 12:17:14 -0700399 private void setStreamVolumeIndex(int stream, int index) {
400 AudioSystem.setStreamVolumeIndex(stream, (index + 5)/10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 }
402
Eric Laurenta553c252009-07-17 12:17:14 -0700403 private int rescaleIndex(int index, int srcStream, int dstStream) {
404 return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex();
405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406
407 ///////////////////////////////////////////////////////////////////////////
408 // IPC methods
409 ///////////////////////////////////////////////////////////////////////////
410
411 /** @see AudioManager#adjustVolume(int, int) */
412 public void adjustVolume(int direction, int flags) {
413 adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags);
414 }
415
416 /** @see AudioManager#adjustVolume(int, int, int) */
417 public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
418
419 int streamType = getActiveStreamType(suggestedStreamType);
420
421 // Don't play sound on other streams
422 if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) {
423 flags &= ~AudioManager.FLAG_PLAY_SOUND;
424 }
425
426 adjustStreamVolume(streamType, direction, flags);
427 }
428
429 /** @see AudioManager#adjustStreamVolume(int, int, int) */
430 public void adjustStreamVolume(int streamType, int direction, int flags) {
431 ensureValidDirection(direction);
432 ensureValidStreamType(streamType);
433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434
Eric Laurenta553c252009-07-17 12:17:14 -0700435 VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
Eric Laurent5b4e6542010-03-19 20:02:21 -0700436 final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 boolean adjustVolume = true;
438
439 // If either the client forces allowing ringer modes for this adjustment,
440 // or the stream type is one that is affected by ringer modes
441 if ((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0
Eric Laurenta553c252009-07-17 12:17:14 -0700442 || streamType == AudioSystem.STREAM_RING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 // Check if the ringer mode changes with this volume adjustment. If
444 // it does, it will handle adjusting the volume, so we won't below
445 adjustVolume = checkForRingerModeChange(oldIndex, direction);
446 }
447
Eric Laurent5b4e6542010-03-19 20:02:21 -0700448 // If stream is muted, adjust last audible index only
449 int index;
450 if (streamState.muteCount() != 0) {
451 if (adjustVolume) {
452 streamState.adjustLastAudibleIndex(direction);
453 // Post a persist volume msg
454 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
455 SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
456 }
457 index = streamState.mLastAudibleIndex;
458 } else {
459 if (adjustVolume && streamState.adjustIndex(direction)) {
460 // Post message to set system volume (it in turn will post a message
461 // to persist). Do not change volume if stream is muted.
Eric Laurenta553c252009-07-17 12:17:14 -0700462 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, STREAM_VOLUME_ALIAS[streamType], SENDMSG_NOOP, 0, 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 streamState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
Eric Laurent5b4e6542010-03-19 20:02:21 -0700465 index = streamState.mIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 // UI
468 mVolumePanel.postVolumeChanged(streamType, flags);
469 // Broadcast Intent
Eric Laurent5b4e6542010-03-19 20:02:21 -0700470 sendVolumeUpdate(streamType, oldIndex, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 }
472
473 /** @see AudioManager#setStreamVolume(int, int, int) */
474 public void setStreamVolume(int streamType, int index, int flags) {
475 ensureValidStreamType(streamType);
Eric Laurent5b4e6542010-03-19 20:02:21 -0700476 VolumeStreamState streamState = mStreamStates[STREAM_VOLUME_ALIAS[streamType]];
Eric Laurent9ce379a2010-02-16 06:00:26 -0800477
Eric Laurent5b4e6542010-03-19 20:02:21 -0700478 final int oldIndex = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
Eric Laurent9ce379a2010-02-16 06:00:26 -0800479
Eric Laurenta553c252009-07-17 12:17:14 -0700480 index = rescaleIndex(index * 10, streamType, STREAM_VOLUME_ALIAS[streamType]);
481 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482
Eric Laurent5b4e6542010-03-19 20:02:21 -0700483 index = (streamState.muteCount() != 0) ? streamState.mLastAudibleIndex : streamState.mIndex;
484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 // UI, etc.
486 mVolumePanel.postVolumeChanged(streamType, flags);
487 // Broadcast Intent
Eric Laurent9ce379a2010-02-16 06:00:26 -0800488 sendVolumeUpdate(streamType, oldIndex, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490
Eric Laurent9ce379a2010-02-16 06:00:26 -0800491 private void sendVolumeUpdate(int streamType, int oldIndex, int index) {
492 oldIndex = (oldIndex + 5) / 10;
493 index = (index + 5) / 10;
494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION);
496 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType);
Eric Laurent9ce379a2010-02-16 06:00:26 -0800497 intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index);
498 intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499
Eric Laurent9ce379a2010-02-16 06:00:26 -0800500 mContext.sendBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 }
502
503 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 * Sets the stream state's index, and posts a message to set system volume.
505 * This will not call out to the UI. Assumes a valid stream type.
506 *
507 * @param streamType Type of the stream
508 * @param index Desired volume index of the stream
509 * @param force If true, set the volume even if the desired volume is same
510 * as the current volume.
Eric Laurent9bcf4012009-06-12 06:09:28 -0700511 * @param lastAudible If true, stores new index as last audible one
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 */
Eric Laurent9bcf4012009-06-12 06:09:28 -0700513 private void setStreamVolumeInt(int streamType, int index, boolean force, boolean lastAudible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurent5b4e6542010-03-19 20:02:21 -0700515
516 // If stream is muted, set last audible index only
517 if (streamState.muteCount() != 0) {
Eric Laurent758dd522010-04-13 10:38:05 -0700518 // Do not allow last audible index to be 0
519 if (index != 0) {
520 streamState.setLastAudibleIndex(index);
521 // Post a persist volume msg
522 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamType,
523 SENDMSG_REPLACE, 0, 1, streamState, PERSIST_DELAY);
524 }
Eric Laurent5b4e6542010-03-19 20:02:21 -0700525 } else {
526 if (streamState.setIndex(index, lastAudible) || force) {
527 // Post message to set system volume (it in turn will post a message
528 // to persist).
Eric Laurent758dd522010-04-13 10:38:05 -0700529 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, streamType, SENDMSG_NOOP, 0, 0,
530 streamState, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 }
532 }
533 }
534
535 /** @see AudioManager#setStreamSolo(int, boolean) */
536 public void setStreamSolo(int streamType, boolean state, IBinder cb) {
537 for (int stream = 0; stream < mStreamStates.length; stream++) {
538 if (!isStreamAffectedByMute(stream) || stream == streamType) continue;
539 // Bring back last audible volume
540 mStreamStates[stream].mute(cb, state);
541 }
542 }
543
544 /** @see AudioManager#setStreamMute(int, boolean) */
545 public void setStreamMute(int streamType, boolean state, IBinder cb) {
546 if (isStreamAffectedByMute(streamType)) {
547 mStreamStates[streamType].mute(cb, state);
548 }
549 }
550
551 /** @see AudioManager#getStreamVolume(int) */
552 public int getStreamVolume(int streamType) {
553 ensureValidStreamType(streamType);
Eric Laurenta553c252009-07-17 12:17:14 -0700554 return (mStreamStates[streamType].mIndex + 5) / 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 }
556
557 /** @see AudioManager#getStreamMaxVolume(int) */
558 public int getStreamMaxVolume(int streamType) {
559 ensureValidStreamType(streamType);
Eric Laurenta553c252009-07-17 12:17:14 -0700560 return (mStreamStates[streamType].getMaxIndex() + 5) / 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 }
562
563 /** @see AudioManager#getRingerMode() */
564 public int getRingerMode() {
565 return mRingerMode;
566 }
567
568 /** @see AudioManager#setRingerMode(int) */
569 public void setRingerMode(int ringerMode) {
Eric Laurenta553c252009-07-17 12:17:14 -0700570 synchronized (mSettingsLock) {
571 if (ringerMode != mRingerMode) {
572 setRingerModeInt(ringerMode, true);
573 // Send sticky broadcast
574 broadcastRingerMode();
575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 }
577 }
578
Eric Laurent4050c932009-07-08 02:52:14 -0700579 private void setRingerModeInt(int ringerMode, boolean persist) {
Jason Parekhb1096152009-03-24 17:48:25 -0700580 mRingerMode = ringerMode;
581
Eric Laurent5b4e6542010-03-19 20:02:21 -0700582 // Mute stream if not previously muted by ringer mode and ringer mode
583 // is not RINGER_MODE_NORMAL and stream is affected by ringer mode.
584 // Unmute stream if previously muted by ringer mode and ringer mode
585 // is RINGER_MODE_NORMAL or stream is not affected by ringer mode.
Jason Parekhb1096152009-03-24 17:48:25 -0700586 int numStreamTypes = AudioSystem.getNumStreamTypes();
Eric Laurent5b4e6542010-03-19 20:02:21 -0700587 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
588 if (isStreamMutedByRingerMode(streamType)) {
589 if (!isStreamAffectedByRingerMode(streamType) ||
590 mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
591 mStreamStates[streamType].mute(null, false);
592 mRingerModeMutedStreams &= ~(1 << streamType);
Eric Laurent9bcf4012009-06-12 06:09:28 -0700593 }
Eric Laurent5b4e6542010-03-19 20:02:21 -0700594 } else {
595 if (isStreamAffectedByRingerMode(streamType) &&
596 mRingerMode != AudioManager.RINGER_MODE_NORMAL) {
597 mStreamStates[streamType].mute(null, true);
598 mRingerModeMutedStreams |= (1 << streamType);
599 }
Jason Parekhb1096152009-03-24 17:48:25 -0700600 }
601 }
Eric Laurenta553c252009-07-17 12:17:14 -0700602
Jason Parekhb1096152009-03-24 17:48:25 -0700603 // Post a persist ringer mode msg
Eric Laurent4050c932009-07-08 02:52:14 -0700604 if (persist) {
605 sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SHARED_MSG,
606 SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY);
607 }
Jason Parekhb1096152009-03-24 17:48:25 -0700608 }
609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 /** @see AudioManager#shouldVibrate(int) */
611 public boolean shouldVibrate(int vibrateType) {
612
613 switch (getVibrateSetting(vibrateType)) {
614
615 case AudioManager.VIBRATE_SETTING_ON:
616 return mRingerMode != AudioManager.RINGER_MODE_SILENT;
617
618 case AudioManager.VIBRATE_SETTING_ONLY_SILENT:
619 return mRingerMode == AudioManager.RINGER_MODE_VIBRATE;
620
621 case AudioManager.VIBRATE_SETTING_OFF:
Daniel Sandlerbcac4962010-04-12 13:23:57 -0400622 // return false, even for incoming calls
623 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624
625 default:
626 return false;
627 }
628 }
629
630 /** @see AudioManager#getVibrateSetting(int) */
631 public int getVibrateSetting(int vibrateType) {
632 return (mVibrateSetting >> (vibrateType * 2)) & 3;
633 }
634
635 /** @see AudioManager#setVibrateSetting(int, int) */
636 public void setVibrateSetting(int vibrateType, int vibrateSetting) {
637
638 mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting);
639
640 // Broadcast change
641 broadcastVibrateSetting(vibrateType);
642
643 // Post message to set ringer mode (it in turn will post a message
644 // to persist)
645 sendMsg(mAudioHandler, MSG_PERSIST_VIBRATE_SETTING, SHARED_MSG, SENDMSG_NOOP, 0, 0,
646 null, 0);
647 }
648
649 /**
650 * @see #setVibrateSetting(int, int)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 */
652 public static int getValueForVibrateSetting(int existingValue, int vibrateType,
653 int vibrateSetting) {
654
655 // First clear the existing setting. Each vibrate type has two bits in
656 // the value. Note '3' is '11' in binary.
657 existingValue &= ~(3 << (vibrateType * 2));
658
659 // Set into the old value
660 existingValue |= (vibrateSetting & 3) << (vibrateType * 2);
661
662 return existingValue;
663 }
664
Eric Laurent9272b4b2010-01-23 17:12:59 -0800665 private class SetModeDeathHandler implements IBinder.DeathRecipient {
666 private IBinder mCb; // To be notified of client's death
667 private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client
668
669 SetModeDeathHandler(IBinder cb) {
670 mCb = cb;
671 }
672
673 public void binderDied() {
674 synchronized(mSetModeDeathHandlers) {
675 Log.w(TAG, "setMode() client died");
676 int index = mSetModeDeathHandlers.indexOf(this);
677 if (index < 0) {
678 Log.w(TAG, "unregistered setMode() client died");
679 } else {
680 mSetModeDeathHandlers.remove(this);
681 // If dead client was a the top of client list,
682 // apply next mode in the stack
683 if (index == 0) {
684 // mSetModeDeathHandlers is never empty as the initial entry
685 // created when AudioService starts is never removed
686 SetModeDeathHandler hdlr = mSetModeDeathHandlers.get(0);
687 int mode = hdlr.getMode();
688 if (AudioService.this.mMode != mode) {
689 if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
690 AudioService.this.mMode = mode;
691 }
692 }
693 }
694 }
695 }
696 }
697
698 public void setMode(int mode) {
699 mMode = mode;
700 }
701
702 public int getMode() {
703 return mMode;
704 }
705
706 public IBinder getBinder() {
707 return mCb;
708 }
709 }
710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 /** @see AudioManager#setMode(int) */
Eric Laurent9272b4b2010-01-23 17:12:59 -0800712 public void setMode(int mode, IBinder cb) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 if (!checkAudioSettingsPermission("setMode()")) {
714 return;
715 }
Eric Laurenta553c252009-07-17 12:17:14 -0700716
717 if (mode < AudioSystem.MODE_CURRENT || mode > AudioSystem.MODE_IN_CALL) {
718 return;
719 }
720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 synchronized (mSettingsLock) {
Eric Laurenta553c252009-07-17 12:17:14 -0700722 if (mode == AudioSystem.MODE_CURRENT) {
723 mode = mMode;
724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (mode != mMode) {
Eric Laurenta553c252009-07-17 12:17:14 -0700726 if (AudioSystem.setPhoneState(mode) == AudioSystem.AUDIO_STATUS_OK) {
Eric Laurentb9c9d262009-05-06 08:13:20 -0700727 mMode = mode;
Eric Laurent9272b4b2010-01-23 17:12:59 -0800728
729 synchronized(mSetModeDeathHandlers) {
730 SetModeDeathHandler hdlr = null;
731 Iterator iter = mSetModeDeathHandlers.iterator();
732 while (iter.hasNext()) {
733 SetModeDeathHandler h = (SetModeDeathHandler)iter.next();
734 if (h.getBinder() == cb) {
735 hdlr = h;
736 // Remove from client list so that it is re-inserted at top of list
737 iter.remove();
738 break;
739 }
740 }
741 if (hdlr == null) {
742 hdlr = new SetModeDeathHandler(cb);
743 // cb is null when setMode() is called by AudioService constructor
744 if (cb != null) {
745 // Register for client death notification
746 try {
747 cb.linkToDeath(hdlr, 0);
748 } catch (RemoteException e) {
749 // Client has died!
750 Log.w(TAG, "setMode() could not link to "+cb+" binder death");
751 }
752 }
753 }
754 // Last client to call setMode() is always at top of client list
755 // as required by SetModeDeathHandler.binderDied()
756 mSetModeDeathHandlers.add(0, hdlr);
757 hdlr.setMode(mode);
758 }
Eric Laurent3def1ee2010-03-17 23:26:26 -0700759
760 if (mode != AudioSystem.MODE_NORMAL) {
761 clearAllScoClients();
762 }
Eric Laurentb9c9d262009-05-06 08:13:20 -0700763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 }
765 int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
Eric Laurenta553c252009-07-17 12:17:14 -0700766 int index = mStreamStates[STREAM_VOLUME_ALIAS[streamType]].mIndex;
Eric Laurent5b4e6542010-03-19 20:02:21 -0700767 setStreamVolumeInt(STREAM_VOLUME_ALIAS[streamType], index, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769 }
770
771 /** @see AudioManager#getMode() */
772 public int getMode() {
773 return mMode;
774 }
775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 /** @see AudioManager#playSoundEffect(int) */
777 public void playSoundEffect(int effectType) {
778 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
Eric Laurenta2ef57d2009-09-28 04:46:10 -0700779 effectType, -1, null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
781
782 /** @see AudioManager#playSoundEffect(int, float) */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 public void playSoundEffectVolume(int effectType, float volume) {
Eric Laurenta2ef57d2009-09-28 04:46:10 -0700784 loadSoundEffects();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SHARED_MSG, SENDMSG_NOOP,
786 effectType, (int) (volume * 1000), null, 0);
787 }
788
789 /**
790 * Loads samples into the soundpool.
791 * This method must be called at when sound effects are enabled
792 */
793 public boolean loadSoundEffects() {
794 synchronized (mSoundEffectsLock) {
Eric Laurenta2ef57d2009-09-28 04:46:10 -0700795 if (mSoundPool != null) {
796 return true;
797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0);
799 if (mSoundPool == null) {
800 return false;
801 }
802 /*
803 * poolId table: The value -1 in this table indicates that corresponding
804 * file (same index in SOUND_EFFECT_FILES[] has not been loaded.
805 * Once loaded, the value in poolId is the sample ID and the same
806 * sample can be reused for another effect using the same file.
807 */
808 int[] poolId = new int[SOUND_EFFECT_FILES.length];
809 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
810 poolId[fileIdx] = -1;
811 }
812 /*
813 * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded.
814 * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
815 * this indicates we have a valid sample loaded for this effect.
816 */
817 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
818 // Do not load sample if this effect uses the MediaPlayer
819 if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
820 continue;
821 }
822 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
823 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
824 int sampleId = mSoundPool.load(filePath, 0);
825 SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
826 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
827 if (sampleId <= 0) {
828 Log.w(TAG, "Soundpool could not load file: "+filePath);
829 }
830 } else {
831 SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
832 }
833 }
834 }
835
836 return true;
837 }
838
839 /**
840 * Unloads samples from the sound pool.
841 * This method can be called to free some memory when
842 * sound effects are disabled.
843 */
844 public void unloadSoundEffects() {
845 synchronized (mSoundEffectsLock) {
846 if (mSoundPool == null) {
847 return;
848 }
849 int[] poolId = new int[SOUND_EFFECT_FILES.length];
850 for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
851 poolId[fileIdx] = 0;
852 }
853
854 for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
855 if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) {
856 continue;
857 }
858 if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) {
859 mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]);
860 SOUND_EFFECT_FILES_MAP[effect][1] = -1;
861 poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
862 }
863 }
864 mSoundPool = null;
865 }
866 }
867
Eric Laurent4050c932009-07-08 02:52:14 -0700868 /** @see AudioManager#reloadAudioSettings() */
869 public void reloadAudioSettings() {
870 // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
871 readPersistedSettings();
872
873 // restore volume settings
874 int numStreamTypes = AudioSystem.getNumStreamTypes();
875 for (int streamType = 0; streamType < numStreamTypes; streamType++) {
876 VolumeStreamState streamState = mStreamStates[streamType];
877
Eric Laurentd25ae672009-07-27 02:12:30 -0700878 String settingName = System.VOLUME_SETTINGS[STREAM_VOLUME_ALIAS[streamType]];
879 String lastAudibleSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
880 int index = Settings.System.getInt(mContentResolver,
881 settingName,
882 AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
883 if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
884 index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
885 } else {
886 index *= 10;
Eric Laurent4050c932009-07-08 02:52:14 -0700887 }
Eric Laurentd25ae672009-07-27 02:12:30 -0700888 streamState.mIndex = streamState.getValidIndex(index);
889
890 index = (index + 5) / 10;
891 index = Settings.System.getInt(mContentResolver,
892 lastAudibleSettingName,
893 (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
894 if (STREAM_VOLUME_ALIAS[streamType] != streamType) {
895 index = rescaleIndex(index * 10, STREAM_VOLUME_ALIAS[streamType], streamType);
896 } else {
897 index *= 10;
898 }
899 streamState.mLastAudibleIndex = streamState.getValidIndex(index);
Eric Laurenta553c252009-07-17 12:17:14 -0700900
Eric Laurent5b4e6542010-03-19 20:02:21 -0700901 // unmute stream that was muted but is not affect by mute anymore
Eric Laurent4050c932009-07-08 02:52:14 -0700902 if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) {
903 int size = streamState.mDeathHandlers.size();
904 for (int i = 0; i < size; i++) {
905 streamState.mDeathHandlers.get(i).mMuteCount = 1;
906 streamState.mDeathHandlers.get(i).mute(false);
907 }
908 }
909 // apply stream volume
910 if (streamState.muteCount() == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -0700911 setStreamVolumeIndex(streamType, streamState.mIndex);
Eric Laurent4050c932009-07-08 02:52:14 -0700912 }
913 }
914
915 // apply new ringer mode
916 setRingerModeInt(getRingerMode(), false);
917 }
918
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700919 /** @see AudioManager#setSpeakerphoneOn() */
920 public void setSpeakerphoneOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -0700921 if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) {
922 return;
923 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700924 if (on) {
925 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_SPEAKER);
926 mForcedUseForComm = AudioSystem.FORCE_SPEAKER;
927 } else {
928 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
929 mForcedUseForComm = AudioSystem.FORCE_NONE;
930 }
931 }
932
933 /** @see AudioManager#isSpeakerphoneOn() */
934 public boolean isSpeakerphoneOn() {
935 if (mForcedUseForComm == AudioSystem.FORCE_SPEAKER) {
936 return true;
937 } else {
938 return false;
939 }
940 }
941
942 /** @see AudioManager#setBluetoothScoOn() */
943 public void setBluetoothScoOn(boolean on){
Eric Laurentdc1d17a2009-09-10 00:48:21 -0700944 if (!checkAudioSettingsPermission("setBluetoothScoOn()")) {
945 return;
946 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700947 if (on) {
948 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_BT_SCO);
Eric Laurentd5603c12009-08-06 08:49:39 -0700949 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_BT_SCO);
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700950 mForcedUseForComm = AudioSystem.FORCE_BT_SCO;
951 } else {
952 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, AudioSystem.FORCE_NONE);
Eric Laurentd5603c12009-08-06 08:49:39 -0700953 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, AudioSystem.FORCE_NONE);
Eric Laurentc42ac9d2009-07-29 08:53:03 -0700954 mForcedUseForComm = AudioSystem.FORCE_NONE;
955 }
956 }
957
958 /** @see AudioManager#isBluetoothScoOn() */
959 public boolean isBluetoothScoOn() {
960 if (mForcedUseForComm == AudioSystem.FORCE_BT_SCO) {
961 return true;
962 } else {
963 return false;
964 }
965 }
966
Eric Laurent3def1ee2010-03-17 23:26:26 -0700967 /** @see AudioManager#startBluetoothSco() */
968 public void startBluetoothSco(IBinder cb){
969 if (!checkAudioSettingsPermission("startBluetoothSco()")) {
970 return;
971 }
972 ScoClient client = getScoClient(cb);
973 client.incCount();
974 }
975
976 /** @see AudioManager#stopBluetoothSco() */
977 public void stopBluetoothSco(IBinder cb){
978 if (!checkAudioSettingsPermission("stopBluetoothSco()")) {
979 return;
980 }
981 ScoClient client = getScoClient(cb);
982 client.decCount();
983 }
984
985 private class ScoClient implements IBinder.DeathRecipient {
986 private IBinder mCb; // To be notified of client's death
987 private int mStartcount; // number of SCO connections started by this client
988
989 ScoClient(IBinder cb) {
990 mCb = cb;
991 mStartcount = 0;
992 }
993
994 public void binderDied() {
995 synchronized(mScoClients) {
996 Log.w(TAG, "SCO client died");
997 int index = mScoClients.indexOf(this);
998 if (index < 0) {
999 Log.w(TAG, "unregistered SCO client died");
1000 } else {
1001 clearCount(true);
1002 mScoClients.remove(this);
1003 }
1004 }
1005 }
1006
1007 public void incCount() {
1008 synchronized(mScoClients) {
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001009 requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED);
Eric Laurent3def1ee2010-03-17 23:26:26 -07001010 if (mStartcount == 0) {
1011 try {
1012 mCb.linkToDeath(this, 0);
1013 } catch (RemoteException e) {
1014 // client has already died!
1015 Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death");
1016 }
1017 }
1018 mStartcount++;
1019 }
1020 }
1021
1022 public void decCount() {
1023 synchronized(mScoClients) {
1024 if (mStartcount == 0) {
1025 Log.w(TAG, "ScoClient.decCount() already 0");
1026 } else {
1027 mStartcount--;
1028 if (mStartcount == 0) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07001029 try {
1030 mCb.unlinkToDeath(this, 0);
1031 } catch (NoSuchElementException e) {
1032 Log.w(TAG, "decCount() going to 0 but not registered to binder");
1033 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07001034 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001035 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
Eric Laurent3def1ee2010-03-17 23:26:26 -07001036 }
1037 }
1038 }
1039
1040 public void clearCount(boolean stopSco) {
1041 synchronized(mScoClients) {
Eric Laurente2dd8c42010-06-30 19:41:56 -07001042 if (mStartcount != 0) {
1043 try {
1044 mCb.unlinkToDeath(this, 0);
1045 } catch (NoSuchElementException e) {
1046 Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder");
1047 }
1048 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07001049 mStartcount = 0;
Eric Laurent3def1ee2010-03-17 23:26:26 -07001050 if (stopSco) {
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001051 requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
Eric Laurent3def1ee2010-03-17 23:26:26 -07001052 }
1053 }
1054 }
1055
1056 public int getCount() {
1057 return mStartcount;
1058 }
1059
1060 public IBinder getBinder() {
1061 return mCb;
1062 }
1063
1064 public int totalCount() {
1065 synchronized(mScoClients) {
1066 int count = 0;
1067 int size = mScoClients.size();
1068 for (int i = 0; i < size; i++) {
1069 count += mScoClients.get(i).getCount();
1070 }
1071 return count;
1072 }
1073 }
1074
1075 private void requestScoState(int state) {
1076 if (totalCount() == 0 &&
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001077 mBluetoothHeadsetDevice != null &&
Eric Laurent3def1ee2010-03-17 23:26:26 -07001078 AudioService.this.mMode == AudioSystem.MODE_NORMAL) {
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001079 if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
1080 mBluetoothHeadset.startVoiceRecognition(mBluetoothHeadsetDevice);
Eric Laurent3def1ee2010-03-17 23:26:26 -07001081 } else {
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001082 mBluetoothHeadset.stopVoiceRecognition(mBluetoothHeadsetDevice);
Eric Laurent3def1ee2010-03-17 23:26:26 -07001083 }
1084 }
1085 }
1086 }
1087
1088 public ScoClient getScoClient(IBinder cb) {
1089 synchronized(mScoClients) {
1090 ScoClient client;
1091 int size = mScoClients.size();
1092 for (int i = 0; i < size; i++) {
1093 client = mScoClients.get(i);
1094 if (client.getBinder() == cb)
1095 return client;
1096 }
1097 client = new ScoClient(cb);
1098 mScoClients.add(client);
1099 return client;
1100 }
1101 }
1102
1103 public void clearAllScoClients() {
1104 synchronized(mScoClients) {
1105 int size = mScoClients.size();
1106 for (int i = 0; i < size; i++) {
1107 mScoClients.get(i).clearCount(false);
1108 }
1109 }
1110 }
1111
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001112 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1113 new BluetoothProfile.ServiceListener() {
1114 public void onServiceConnected(int profile, BluetoothProfile proxy) {
1115 mBluetoothHeadset = (BluetoothHeadset) proxy;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001116 List<BluetoothDevice> deviceList = mBluetoothHeadset.getConnectedDevices();
1117 if (deviceList.size() > 0) {
1118 mBluetoothHeadsetDevice = deviceList.get(0);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001119 } else {
1120 mBluetoothHeadsetDevice = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07001121 }
1122 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001123 public void onServiceDisconnected(int profile) {
Jaikumar Ganesh740e39b2010-06-02 12:33:53 -07001124 if (mBluetoothHeadset != null) {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001125 List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001126 if (devices.size() == 0) {
1127 mBluetoothHeadsetDevice = null;
Jaikumar Ganesh740e39b2010-06-02 12:33:53 -07001128 clearAllScoClients();
1129 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001130 mBluetoothHeadset = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07001131 }
1132 }
1133 };
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08001134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 ///////////////////////////////////////////////////////////////////////////
1136 // Internal methods
1137 ///////////////////////////////////////////////////////////////////////////
1138
1139 /**
1140 * Checks if the adjustment should change ringer mode instead of just
1141 * adjusting volume. If so, this will set the proper ringer mode and volume
1142 * indices on the stream states.
1143 */
1144 private boolean checkForRingerModeChange(int oldIndex, int direction) {
1145 boolean adjustVolumeIndex = true;
1146 int newRingerMode = mRingerMode;
1147
Daniel Sandler6329bf72010-02-26 15:17:44 -05001148 if (mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
1149 // audible mode, at the bottom of the scale
1150 if (direction == AudioManager.ADJUST_LOWER
1151 && (oldIndex + 5) / 10 == 1) {
1152 // "silent mode", but which one?
1153 newRingerMode = System.getInt(mContentResolver, System.VIBRATE_IN_SILENT, 1) == 1
1154 ? AudioManager.RINGER_MODE_VIBRATE
1155 : AudioManager.RINGER_MODE_SILENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
Daniel Sandler6329bf72010-02-26 15:17:44 -05001157 } else {
1158 if (direction == AudioManager.ADJUST_RAISE) {
1159 // exiting silent mode
1160 newRingerMode = AudioManager.RINGER_MODE_NORMAL;
Eric Laurent527c3ab2010-04-13 08:31:02 -07001161 } else {
1162 // prevent last audible index to reach 0
1163 adjustVolumeIndex = false;
Daniel Sandler6329bf72010-02-26 15:17:44 -05001164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
1167 if (newRingerMode != mRingerMode) {
1168 setRingerMode(newRingerMode);
1169
1170 /*
1171 * If we are changing ringer modes, do not increment/decrement the
1172 * volume index. Instead, the handler for the message above will
1173 * take care of changing the index.
1174 */
1175 adjustVolumeIndex = false;
1176 }
1177
1178 return adjustVolumeIndex;
1179 }
1180
1181 public boolean isStreamAffectedByRingerMode(int streamType) {
Eric Laurent9bcf4012009-06-12 06:09:28 -07001182 return (mRingerModeAffectedStreams & (1 << streamType)) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184
Eric Laurent5b4e6542010-03-19 20:02:21 -07001185 private boolean isStreamMutedByRingerMode(int streamType) {
1186 return (mRingerModeMutedStreams & (1 << streamType)) != 0;
1187 }
1188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 public boolean isStreamAffectedByMute(int streamType) {
1190 return (mMuteAffectedStreams & (1 << streamType)) != 0;
1191 }
1192
1193 private void ensureValidDirection(int direction) {
1194 if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) {
1195 throw new IllegalArgumentException("Bad direction " + direction);
1196 }
1197 }
1198
1199 private void ensureValidStreamType(int streamType) {
1200 if (streamType < 0 || streamType >= mStreamStates.length) {
1201 throw new IllegalArgumentException("Bad stream type " + streamType);
1202 }
1203 }
1204
1205 private int getActiveStreamType(int suggestedStreamType) {
1206 boolean isOffhook = false;
1207 try {
1208 ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
1209 if (phone != null) isOffhook = phone.isOffhook();
1210 } catch (RemoteException e) {
1211 Log.w(TAG, "Couldn't connect to phone service", e);
1212 }
1213
Eric Laurenta553c252009-07-17 12:17:14 -07001214 if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO...");
1216 return AudioSystem.STREAM_BLUETOOTH_SCO;
Eric Laurent23f25cd2010-01-25 08:49:09 -08001217 } else if (isOffhook || AudioSystem.isStreamActive(AudioSystem.STREAM_VOICE_CALL)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL...");
1219 return AudioSystem.STREAM_VOICE_CALL;
Eric Laurent23f25cd2010-01-25 08:49:09 -08001220 } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC...");
1222 return AudioSystem.STREAM_MUSIC;
1223 } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1224 // Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING...");
1225 return AudioSystem.STREAM_RING;
1226 } else {
1227 // Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType);
1228 return suggestedStreamType;
1229 }
1230 }
1231
1232 private void broadcastRingerMode() {
1233 // Send sticky broadcast
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001234 Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION);
1235 broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, mRingerMode);
1236 broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
1237 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
1238 long origCallerIdentityToken = Binder.clearCallingIdentity();
1239 mContext.sendStickyBroadcast(broadcast);
1240 Binder.restoreCallingIdentity(origCallerIdentityToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
1242
1243 private void broadcastVibrateSetting(int vibrateType) {
1244 // Send broadcast
1245 if (ActivityManagerNative.isSystemReady()) {
1246 Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION);
1247 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType);
1248 broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType));
1249 mContext.sendBroadcast(broadcast);
1250 }
1251 }
1252
1253 // Message helper methods
1254 private static int getMsg(int baseMsg, int streamType) {
1255 return (baseMsg & 0xffff) | streamType << 16;
1256 }
1257
1258 private static int getMsgBase(int msg) {
1259 return msg & 0xffff;
1260 }
1261
1262 private static void sendMsg(Handler handler, int baseMsg, int streamType,
1263 int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) {
1264 int msg = (streamType == SHARED_MSG) ? baseMsg : getMsg(baseMsg, streamType);
1265
1266 if (existingMsgPolicy == SENDMSG_REPLACE) {
1267 handler.removeMessages(msg);
1268 } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) {
1269 return;
1270 }
1271
1272 handler
1273 .sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay);
1274 }
1275
1276 boolean checkAudioSettingsPermission(String method) {
1277 if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS")
1278 == PackageManager.PERMISSION_GRANTED) {
1279 return true;
1280 }
1281 String msg = "Audio Settings Permission Denial: " + method + " from pid="
1282 + Binder.getCallingPid()
1283 + ", uid=" + Binder.getCallingUid();
1284 Log.w(TAG, msg);
1285 return false;
1286 }
1287
1288
1289 ///////////////////////////////////////////////////////////////////////////
1290 // Inner classes
1291 ///////////////////////////////////////////////////////////////////////////
1292
1293 public class VolumeStreamState {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 private final int mStreamType;
1295
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07001296 private String mVolumeIndexSettingName;
1297 private String mLastAudibleVolumeIndexSettingName;
Eric Laurenta553c252009-07-17 12:17:14 -07001298 private int mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 private int mIndex;
1300 private int mLastAudibleIndex;
1301 private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo requests client death
1302
Eric Laurenta553c252009-07-17 12:17:14 -07001303 private VolumeStreamState(String settingName, int streamType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07001305 setVolumeIndexSettingName(settingName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306
1307 mStreamType = streamType;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308
1309 final ContentResolver cr = mContentResolver;
Jared Suttles59820132009-08-13 21:50:52 -05001310 mIndexMax = MAX_STREAM_VOLUME[streamType];
Eric Laurenta553c252009-07-17 12:17:14 -07001311 mIndex = Settings.System.getInt(cr,
1312 mVolumeIndexSettingName,
1313 AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1314 mLastAudibleIndex = Settings.System.getInt(cr,
1315 mLastAudibleVolumeIndexSettingName,
1316 (mIndex > 0) ? mIndex : AudioManager.DEFAULT_STREAM_VOLUME[streamType]);
1317 AudioSystem.initStreamVolume(streamType, 0, mIndexMax);
1318 mIndexMax *= 10;
1319 mIndex = getValidIndex(10 * mIndex);
1320 mLastAudibleIndex = getValidIndex(10 * mLastAudibleIndex);
1321 setStreamVolumeIndex(streamType, mIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 mDeathHandlers = new ArrayList<VolumeDeathHandler>();
1323 }
1324
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07001325 public void setVolumeIndexSettingName(String settingName) {
1326 mVolumeIndexSettingName = settingName;
1327 mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE;
1328 }
1329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 public boolean adjustIndex(int deltaIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07001331 return setIndex(mIndex + deltaIndex * 10, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
1333
Eric Laurent9bcf4012009-06-12 06:09:28 -07001334 public boolean setIndex(int index, boolean lastAudible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 int oldIndex = mIndex;
1336 mIndex = getValidIndex(index);
1337
1338 if (oldIndex != mIndex) {
Eric Laurent9bcf4012009-06-12 06:09:28 -07001339 if (lastAudible) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 mLastAudibleIndex = mIndex;
1341 }
Eric Laurenta553c252009-07-17 12:17:14 -07001342 // Apply change to all streams using this one as alias
1343 int numStreamTypes = AudioSystem.getNumStreamTypes();
1344 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1345 if (streamType != mStreamType && STREAM_VOLUME_ALIAS[streamType] == mStreamType) {
1346 mStreamStates[streamType].setIndex(rescaleIndex(mIndex, mStreamType, streamType), lastAudible);
1347 }
1348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 return true;
1350 } else {
1351 return false;
1352 }
1353 }
1354
Eric Laurent5b4e6542010-03-19 20:02:21 -07001355 public void setLastAudibleIndex(int index) {
1356 mLastAudibleIndex = getValidIndex(index);
1357 }
1358
1359 public void adjustLastAudibleIndex(int deltaIndex) {
1360 setLastAudibleIndex(mLastAudibleIndex + deltaIndex * 10);
1361 }
1362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 public int getMaxIndex() {
Eric Laurenta553c252009-07-17 12:17:14 -07001364 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366
1367 public void mute(IBinder cb, boolean state) {
1368 VolumeDeathHandler handler = getDeathHandler(cb, state);
1369 if (handler == null) {
1370 Log.e(TAG, "Could not get client death handler for stream: "+mStreamType);
1371 return;
1372 }
1373 handler.mute(state);
1374 }
1375
1376 private int getValidIndex(int index) {
1377 if (index < 0) {
1378 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001379 } else if (index > mIndexMax) {
1380 return mIndexMax;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382
1383 return index;
1384 }
1385
1386 private class VolumeDeathHandler implements IBinder.DeathRecipient {
1387 private IBinder mICallback; // To be notified of client's death
1388 private int mMuteCount; // Number of active mutes for this client
1389
1390 VolumeDeathHandler(IBinder cb) {
1391 mICallback = cb;
1392 }
1393
1394 public void mute(boolean state) {
1395 synchronized(mDeathHandlers) {
1396 if (state) {
1397 if (mMuteCount == 0) {
1398 // Register for client death notification
1399 try {
Eric Laurent5b4e6542010-03-19 20:02:21 -07001400 // mICallback can be 0 if muted by AudioService
1401 if (mICallback != null) {
1402 mICallback.linkToDeath(this, 0);
1403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 mDeathHandlers.add(this);
1405 // If the stream is not yet muted by any client, set lvel to 0
1406 if (muteCount() == 0) {
Eric Laurent9bcf4012009-06-12 06:09:28 -07001407 setIndex(0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1409 VolumeStreamState.this, 0);
1410 }
1411 } catch (RemoteException e) {
1412 // Client has died!
1413 binderDied();
1414 mDeathHandlers.notify();
1415 return;
1416 }
1417 } else {
1418 Log.w(TAG, "stream: "+mStreamType+" was already muted by this client");
1419 }
1420 mMuteCount++;
1421 } else {
1422 if (mMuteCount == 0) {
1423 Log.e(TAG, "unexpected unmute for stream: "+mStreamType);
1424 } else {
1425 mMuteCount--;
1426 if (mMuteCount == 0) {
1427 // Unregistr from client death notification
1428 mDeathHandlers.remove(this);
Eric Laurent5b4e6542010-03-19 20:02:21 -07001429 // mICallback can be 0 if muted by AudioService
1430 if (mICallback != null) {
1431 mICallback.unlinkToDeath(this, 0);
1432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 if (muteCount() == 0) {
Eric Laurent5b4e6542010-03-19 20:02:21 -07001434 // If the stream is not muted any more, restore it's volume if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 // ringer mode allows it
1436 if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) {
Eric Laurent9bcf4012009-06-12 06:09:28 -07001437 setIndex(mLastAudibleIndex, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 sendMsg(mAudioHandler, MSG_SET_SYSTEM_VOLUME, mStreamType, SENDMSG_NOOP, 0, 0,
1439 VolumeStreamState.this, 0);
1440 }
1441 }
1442 }
1443 }
1444 }
1445 mDeathHandlers.notify();
1446 }
1447 }
1448
1449 public void binderDied() {
1450 Log.w(TAG, "Volume service client died for stream: "+mStreamType);
1451 if (mMuteCount != 0) {
1452 // Reset all active mute requests from this client.
1453 mMuteCount = 1;
1454 mute(false);
1455 }
1456 }
1457 }
1458
1459 private int muteCount() {
1460 int count = 0;
1461 int size = mDeathHandlers.size();
1462 for (int i = 0; i < size; i++) {
1463 count += mDeathHandlers.get(i).mMuteCount;
1464 }
1465 return count;
1466 }
1467
1468 private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) {
1469 synchronized(mDeathHandlers) {
1470 VolumeDeathHandler handler;
1471 int size = mDeathHandlers.size();
1472 for (int i = 0; i < size; i++) {
1473 handler = mDeathHandlers.get(i);
Eric Laurent5b4e6542010-03-19 20:02:21 -07001474 if (cb == handler.mICallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 return handler;
1476 }
1477 }
1478 // If this is the first mute request for this client, create a new
1479 // client death handler. Otherwise, it is an out of sequence unmute request.
1480 if (state) {
1481 handler = new VolumeDeathHandler(cb);
1482 } else {
1483 Log.w(TAG, "stream was not muted by this client");
1484 handler = null;
1485 }
1486 return handler;
1487 }
1488 }
1489 }
1490
1491 /** Thread that handles native AudioSystem control. */
1492 private class AudioSystemThread extends Thread {
1493 AudioSystemThread() {
1494 super("AudioService");
1495 }
1496
1497 @Override
1498 public void run() {
1499 // Set this thread up so the handler will work on it
1500 Looper.prepare();
1501
1502 synchronized(AudioService.this) {
1503 mAudioHandler = new AudioHandler();
1504
1505 // Notify that the handler has been created
1506 AudioService.this.notify();
1507 }
1508
1509 // Listen for volume change requests that are set by VolumePanel
1510 Looper.loop();
1511 }
1512 }
1513
1514 /** Handles internal volume messages in separate volume thread. */
1515 private class AudioHandler extends Handler {
1516
1517 private void setSystemVolume(VolumeStreamState streamState) {
1518
1519 // Adjust volume
Eric Laurenta553c252009-07-17 12:17:14 -07001520 setStreamVolumeIndex(streamState.mStreamType, streamState.mIndex);
1521
1522 // Apply change to all streams using this one as alias
1523 int numStreamTypes = AudioSystem.getNumStreamTypes();
1524 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
1525 if (streamType != streamState.mStreamType &&
1526 STREAM_VOLUME_ALIAS[streamType] == streamState.mStreamType) {
1527 setStreamVolumeIndex(streamType, mStreamStates[streamType].mIndex);
1528 }
1529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530
1531 // Post a persist volume msg
1532 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, streamState.mStreamType,
Eric Laurent31951ca2010-03-02 18:54:45 -08001533 SENDMSG_REPLACE, 1, 1, streamState, PERSIST_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535
Eric Laurent31951ca2010-03-02 18:54:45 -08001536 private void persistVolume(VolumeStreamState streamState, boolean current, boolean lastAudible) {
1537 if (current) {
1538 System.putInt(mContentResolver, streamState.mVolumeIndexSettingName,
1539 (streamState.mIndex + 5)/ 10);
1540 }
1541 if (lastAudible) {
1542 System.putInt(mContentResolver, streamState.mLastAudibleVolumeIndexSettingName,
Eric Laurenta553c252009-07-17 12:17:14 -07001543 (streamState.mLastAudibleIndex + 5) / 10);
Eric Laurent31951ca2010-03-02 18:54:45 -08001544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546
1547 private void persistRingerMode() {
1548 System.putInt(mContentResolver, System.MODE_RINGER, mRingerMode);
1549 }
1550
1551 private void persistVibrateSetting() {
1552 System.putInt(mContentResolver, System.VIBRATE_ON, mVibrateSetting);
1553 }
1554
1555 private void playSoundEffect(int effectType, int volume) {
1556 synchronized (mSoundEffectsLock) {
1557 if (mSoundPool == null) {
1558 return;
1559 }
Eric Laurenta2ef57d2009-09-28 04:46:10 -07001560 float volFloat;
1561 // use STREAM_MUSIC volume attenuated by 3 dB if volume is not specified by caller
1562 if (volume < 0) {
1563 // Same linear to log conversion as in native AudioSystem::linearToLog() (AudioSystem.cpp)
1564 float dBPerStep = (float)((0.5 * 100) / MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
1565 int musicVolIndex = (mStreamStates[AudioSystem.STREAM_MUSIC].mIndex + 5) / 10;
1566 float musicVoldB = dBPerStep * (musicVolIndex - MAX_STREAM_VOLUME[AudioSystem.STREAM_MUSIC]);
1567 volFloat = (float)Math.pow(10, (musicVoldB - 3)/20);
1568 } else {
1569 volFloat = (float) volume / 1000.0f;
1570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571
1572 if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) {
Eric Laurenta2ef57d2009-09-28 04:46:10 -07001573 mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 } else {
1575 MediaPlayer mediaPlayer = new MediaPlayer();
1576 if (mediaPlayer != null) {
1577 try {
1578 String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
1579 mediaPlayer.setDataSource(filePath);
1580 mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM);
1581 mediaPlayer.prepare();
Eric Laurenta2ef57d2009-09-28 04:46:10 -07001582 mediaPlayer.setVolume(volFloat, volFloat);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
1584 public void onCompletion(MediaPlayer mp) {
1585 cleanupPlayer(mp);
1586 }
1587 });
1588 mediaPlayer.setOnErrorListener(new OnErrorListener() {
1589 public boolean onError(MediaPlayer mp, int what, int extra) {
1590 cleanupPlayer(mp);
1591 return true;
1592 }
1593 });
1594 mediaPlayer.start();
1595 } catch (IOException ex) {
1596 Log.w(TAG, "MediaPlayer IOException: "+ex);
1597 } catch (IllegalArgumentException ex) {
1598 Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex);
1599 } catch (IllegalStateException ex) {
1600 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1601 }
1602 }
1603 }
1604 }
1605 }
1606
1607 private void cleanupPlayer(MediaPlayer mp) {
1608 if (mp != null) {
1609 try {
1610 mp.stop();
1611 mp.release();
1612 } catch (IllegalStateException ex) {
1613 Log.w(TAG, "MediaPlayer IllegalStateException: "+ex);
1614 }
1615 }
1616 }
1617
1618 @Override
1619 public void handleMessage(Message msg) {
1620 int baseMsgWhat = getMsgBase(msg.what);
1621
1622 switch (baseMsgWhat) {
1623
1624 case MSG_SET_SYSTEM_VOLUME:
1625 setSystemVolume((VolumeStreamState) msg.obj);
1626 break;
1627
1628 case MSG_PERSIST_VOLUME:
Eric Laurent31951ca2010-03-02 18:54:45 -08001629 persistVolume((VolumeStreamState) msg.obj, (msg.arg1 != 0), (msg.arg2 != 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 break;
1631
1632 case MSG_PERSIST_RINGER_MODE:
1633 persistRingerMode();
1634 break;
1635
1636 case MSG_PERSIST_VIBRATE_SETTING:
1637 persistVibrateSetting();
1638 break;
1639
1640 case MSG_MEDIA_SERVER_DIED:
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 // Force creation of new IAudioflinger interface
Eric Laurent89e74ba2009-09-30 18:26:36 -07001642 if (!mMediaServerOk) {
1643 Log.e(TAG, "Media server died.");
Eric Laurent23f25cd2010-01-25 08:49:09 -08001644 AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC);
Eric Laurent89e74ba2009-09-30 18:26:36 -07001645 sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
1646 null, 500);
1647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 break;
1649
1650 case MSG_MEDIA_SERVER_STARTED:
1651 Log.e(TAG, "Media server started.");
Eric Laurent3c652ca2010-06-21 20:46:26 -07001652 // indicate to audio HAL that we start the reconfiguration phase after a media
1653 // server crash
1654 // Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server
1655 // process restarts after a crash, not the first time it is started.
1656 AudioSystem.setParameters("restarting=true");
1657
Eric Laurentc42ac9d2009-07-29 08:53:03 -07001658 // Restore device connection states
1659 Set set = mConnectedDevices.entrySet();
1660 Iterator i = set.iterator();
1661 while(i.hasNext()){
1662 Map.Entry device = (Map.Entry)i.next();
1663 AudioSystem.setDeviceConnectionState(((Integer)device.getKey()).intValue(),
1664 AudioSystem.DEVICE_STATE_AVAILABLE,
1665 (String)device.getValue());
1666 }
1667
1668 // Restore call state
1669 AudioSystem.setPhoneState(mMode);
1670
Eric Laurentd5603c12009-08-06 08:49:39 -07001671 // Restore forced usage for communcations and record
Eric Laurentc42ac9d2009-07-29 08:53:03 -07001672 AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm);
Eric Laurentd5603c12009-08-06 08:49:39 -07001673 AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm);
Eric Laurentc42ac9d2009-07-29 08:53:03 -07001674
Eric Laurenta553c252009-07-17 12:17:14 -07001675 // Restore stream volumes
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 int numStreamTypes = AudioSystem.getNumStreamTypes();
1677 for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
Eric Laurenta553c252009-07-17 12:17:14 -07001678 int index;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 VolumeStreamState streamState = mStreamStates[streamType];
Eric Laurentc42ac9d2009-07-29 08:53:03 -07001680 AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 if (streamState.muteCount() == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001682 index = streamState.mIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07001684 index = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
Eric Laurenta553c252009-07-17 12:17:14 -07001686 setStreamVolumeIndex(streamType, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
Eric Laurentc42ac9d2009-07-29 08:53:03 -07001688
1689 // Restore ringer mode
1690 setRingerModeInt(getRingerMode(), false);
Eric Laurent3c652ca2010-06-21 20:46:26 -07001691
1692 // indicate the end of reconfiguration phase to audio HAL
1693 AudioSystem.setParameters("restarting=false");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 break;
1695
1696 case MSG_PLAY_SOUND_EFFECT:
1697 playSoundEffect(msg.arg1, msg.arg2);
1698 break;
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001699
1700 case MSG_BTA2DP_DOCK_TIMEOUT:
1701 // msg.obj == address of BTA2DP device
1702 makeA2dpDeviceUnavailableNow( (String) msg.obj );
1703 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 }
1706 }
1707
Jason Parekhb1096152009-03-24 17:48:25 -07001708 private class SettingsObserver extends ContentObserver {
Eric Laurenta553c252009-07-17 12:17:14 -07001709
Jason Parekhb1096152009-03-24 17:48:25 -07001710 SettingsObserver() {
1711 super(new Handler());
1712 mContentResolver.registerContentObserver(Settings.System.getUriFor(
1713 Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this);
Eric Laurenta553c252009-07-17 12:17:14 -07001714 mContentResolver.registerContentObserver(Settings.System.getUriFor(
1715 Settings.System.NOTIFICATIONS_USE_RING_VOLUME), false, this);
Jason Parekhb1096152009-03-24 17:48:25 -07001716 }
1717
1718 @Override
1719 public void onChange(boolean selfChange) {
1720 super.onChange(selfChange);
Eric Laurenta553c252009-07-17 12:17:14 -07001721 synchronized (mSettingsLock) {
1722 int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
1723 Settings.System.MODE_RINGER_STREAMS_AFFECTED,
1724 0);
1725 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
1726 /*
1727 * Ensure all stream types that should be affected by ringer mode
1728 * are in the proper state.
1729 */
1730 mRingerModeAffectedStreams = ringerModeAffectedStreams;
1731 setRingerModeInt(getRingerMode(), false);
1732 }
Eric Laurent9bcf4012009-06-12 06:09:28 -07001733
Eric Laurenta553c252009-07-17 12:17:14 -07001734 int notificationsUseRingVolume = Settings.System.getInt(mContentResolver,
1735 Settings.System.NOTIFICATIONS_USE_RING_VOLUME,
1736 1);
1737 if (notificationsUseRingVolume != mNotificationsUseRingVolume) {
1738 mNotificationsUseRingVolume = notificationsUseRingVolume;
1739 if (mNotificationsUseRingVolume == 1) {
1740 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07001741 mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
1742 System.VOLUME_SETTINGS[AudioSystem.STREAM_RING]);
Eric Laurenta553c252009-07-17 12:17:14 -07001743 } else {
1744 STREAM_VOLUME_ALIAS[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION;
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07001745 mStreamStates[AudioSystem.STREAM_NOTIFICATION].setVolumeIndexSettingName(
1746 System.VOLUME_SETTINGS[AudioSystem.STREAM_NOTIFICATION]);
Eric Laurenta553c252009-07-17 12:17:14 -07001747 // Persist notification volume volume as it was not persisted while aliased to ring volume
Jean-Michel Trivi11a74a72009-10-27 17:39:30 -07001748 // and persist with no delay as there might be registered observers of the persisted
1749 // notification volume.
Eric Laurenta553c252009-07-17 12:17:14 -07001750 sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, AudioSystem.STREAM_NOTIFICATION,
Eric Laurent31951ca2010-03-02 18:54:45 -08001751 SENDMSG_REPLACE, 1, 1, mStreamStates[AudioSystem.STREAM_NOTIFICATION], 0);
Eric Laurenta553c252009-07-17 12:17:14 -07001752 }
1753 }
1754 }
Jason Parekhb1096152009-03-24 17:48:25 -07001755 }
Jason Parekhb1096152009-03-24 17:48:25 -07001756 }
Eric Laurenta553c252009-07-17 12:17:14 -07001757
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001758 private void makeA2dpDeviceAvailable(String address) {
1759 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
1760 AudioSystem.DEVICE_STATE_AVAILABLE,
1761 address);
1762 // Reset A2DP suspend state each time a new sink is connected
1763 AudioSystem.setParameters("A2dpSuspended=false");
1764 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP),
1765 address);
1766 }
1767
1768 private void makeA2dpDeviceUnavailableNow(String address) {
1769 Intent noisyIntent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
1770 mContext.sendBroadcast(noisyIntent);
1771 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
1772 AudioSystem.DEVICE_STATE_UNAVAILABLE,
1773 address);
1774 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
1775 }
1776
1777 private void makeA2dpDeviceUnavailableLater(String address) {
Eric Laurent3b591262010-04-20 07:01:00 -07001778 // prevent any activity on the A2DP audio output to avoid unwanted
1779 // reconnection of the sink.
1780 AudioSystem.setParameters("A2dpSuspended=true");
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001781 // the device will be made unavailable later, so consider it disconnected right away
1782 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP);
1783 // send the delayed message to make the device unavailable later
1784 Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address);
1785 mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS);
1786
1787 }
1788
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07001789 private void cancelA2dpDeviceTimeout() {
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001790 mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT);
1791 }
1792
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07001793 private boolean hasScheduledA2dpDockTimeout() {
1794 return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT);
1795 }
1796
1797 /* cache of the address of the last dock the device was connected to */
1798 private String mDockAddress;
1799
Eric Laurenta553c252009-07-17 12:17:14 -07001800 /**
1801 * Receiver for misc intent broadcasts the Phone app cares about.
1802 */
1803 private class AudioServiceBroadcastReceiver extends BroadcastReceiver {
1804 @Override
1805 public void onReceive(Context context, Intent intent) {
1806 String action = intent.getAction();
1807
Jean-Michel Trivi758559e2010-03-09 09:26:08 -08001808 if (action.equals(Intent.ACTION_DOCK_EVENT)) {
1809 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1810 Intent.EXTRA_DOCK_STATE_UNDOCKED);
1811 int config;
1812 switch (dockState) {
1813 case Intent.EXTRA_DOCK_STATE_DESK:
1814 config = AudioSystem.FORCE_BT_DESK_DOCK;
1815 break;
1816 case Intent.EXTRA_DOCK_STATE_CAR:
1817 config = AudioSystem.FORCE_BT_CAR_DOCK;
1818 break;
1819 case Intent.EXTRA_DOCK_STATE_UNDOCKED:
1820 default:
1821 config = AudioSystem.FORCE_NONE;
1822 }
1823 AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001824 } else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
1825 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
1826 BluetoothProfile.STATE_DISCONNECTED);
Nick Pelly005b2282009-09-10 10:21:56 -07001827 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Nick Pellybd022f42009-08-14 18:33:38 -07001828 String address = btDevice.getAddress();
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001829 boolean isConnected =
1830 (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) &&
1831 mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address));
Eric Laurentd5603c12009-08-06 08:49:39 -07001832
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001833 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001834 if (btDevice.isBluetoothDock()) {
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001835 if (state == BluetoothProfile.STATE_DISCONNECTED) {
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001836 // introduction of a delay for transient disconnections of docks when
1837 // power is rapidly turned off/on, this message will be canceled if
1838 // we reconnect the dock under a preset delay
1839 makeA2dpDeviceUnavailableLater(address);
1840 // the next time isConnected is evaluated, it will be false for the dock
1841 }
1842 } else {
1843 makeA2dpDeviceUnavailableNow(address);
1844 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001845 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001846 if (btDevice.isBluetoothDock()) {
1847 // this could be a reconnection after a transient disconnection
Jean-Michel Trivia847ba42010-04-23 11:49:29 -07001848 cancelA2dpDeviceTimeout();
1849 mDockAddress = address;
1850 } else {
1851 // this could be a connection of another A2DP device before the timeout of
1852 // a dock: cancel the dock timeout, and make the dock unavailable now
1853 if(hasScheduledA2dpDockTimeout()) {
1854 cancelA2dpDeviceTimeout();
1855 makeA2dpDeviceUnavailableNow(mDockAddress);
1856 }
Jean-Michel Trivi4c637b92010-04-12 18:44:10 -07001857 }
1858 makeA2dpDeviceAvailable(address);
Eric Laurenta553c252009-07-17 12:17:14 -07001859 }
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001860 } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
1861 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
1862 BluetoothProfile.STATE_DISCONNECTED);
Eric Laurentd5603c12009-08-06 08:49:39 -07001863 int device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO;
Nick Pelly005b2282009-09-10 10:21:56 -07001864 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Nick Pellya56d1c72009-08-19 14:49:29 -07001865 String address = null;
Nick Pellya56d1c72009-08-19 14:49:29 -07001866 if (btDevice != null) {
1867 address = btDevice.getAddress();
Nick Pelly005b2282009-09-10 10:21:56 -07001868 BluetoothClass btClass = btDevice.getBluetoothClass();
1869 if (btClass != null) {
1870 switch (btClass.getDeviceClass()) {
Nick Pellya56d1c72009-08-19 14:49:29 -07001871 case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
1872 case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
1873 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1874 break;
1875 case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
1876 device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1877 break;
Nick Pellya56d1c72009-08-19 14:49:29 -07001878 }
Eric Laurentd5603c12009-08-06 08:49:39 -07001879 }
1880 }
1881
1882 boolean isConnected = (mConnectedDevices.containsKey(device) &&
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001883 mConnectedDevices.get(device).equals(address));
Eric Laurentd5603c12009-08-06 08:49:39 -07001884
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001885 if (isConnected && state != BluetoothProfile.STATE_CONNECTED) {
Eric Laurentd5603c12009-08-06 08:49:39 -07001886 AudioSystem.setDeviceConnectionState(device,
Eric Laurenta553c252009-07-17 12:17:14 -07001887 AudioSystem.DEVICE_STATE_UNAVAILABLE,
1888 address);
Eric Laurentd5603c12009-08-06 08:49:39 -07001889 mConnectedDevices.remove(device);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001890 mBluetoothHeadsetDevice = null;
Eric Laurent3def1ee2010-03-17 23:26:26 -07001891 clearAllScoClients();
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001892 } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) {
Eric Laurentd5603c12009-08-06 08:49:39 -07001893 AudioSystem.setDeviceConnectionState(device,
Eric Laurenta553c252009-07-17 12:17:14 -07001894 AudioSystem.DEVICE_STATE_AVAILABLE,
1895 address);
Nick Pellybd022f42009-08-14 18:33:38 -07001896 mConnectedDevices.put(new Integer(device), address);
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001897 mBluetoothHeadsetDevice = btDevice;
Eric Laurenta553c252009-07-17 12:17:14 -07001898 }
1899 } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
1900 int state = intent.getIntExtra("state", 0);
Eric Laurent923d7d72009-11-12 12:09:06 -08001901 int microphone = intent.getIntExtra("microphone", 0);
1902
1903 if (microphone != 0) {
1904 boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
1905 if (state == 0 && isConnected) {
1906 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
1907 AudioSystem.DEVICE_STATE_UNAVAILABLE,
1908 "");
1909 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADSET);
1910 } else if (state == 1 && !isConnected) {
1911 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADSET,
1912 AudioSystem.DEVICE_STATE_AVAILABLE,
1913 "");
1914 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADSET), "");
1915 }
1916 } else {
1917 boolean isConnected = mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
1918 if (state == 0 && isConnected) {
1919 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
1920 AudioSystem.DEVICE_STATE_UNAVAILABLE,
1921 "");
1922 mConnectedDevices.remove(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE);
1923 } else if (state == 1 && !isConnected) {
1924 AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE,
1925 AudioSystem.DEVICE_STATE_AVAILABLE,
1926 "");
1927 mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_WIRED_HEADPHONE), "");
1928 }
Eric Laurenta553c252009-07-17 12:17:14 -07001929 }
Eric Laurent3def1ee2010-03-17 23:26:26 -07001930 } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001931 int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
Eric Laurent3def1ee2010-03-17 23:26:26 -07001932 synchronized (mScoClients) {
1933 if (!mScoClients.isEmpty()) {
1934 switch (state) {
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001935 case BluetoothHeadset.STATE_AUDIO_CONNECTED:
Eric Laurent3def1ee2010-03-17 23:26:26 -07001936 state = AudioManager.SCO_AUDIO_STATE_CONNECTED;
1937 break;
Jaikumar Ganesh82aa7f02010-09-27 17:05:10 -07001938 case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
Eric Laurent3def1ee2010-03-17 23:26:26 -07001939 state = AudioManager.SCO_AUDIO_STATE_DISCONNECTED;
1940 break;
1941 default:
1942 state = AudioManager.SCO_AUDIO_STATE_ERROR;
1943 break;
1944 }
1945 if (state != AudioManager.SCO_AUDIO_STATE_ERROR) {
1946 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
1947 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
1948 mContext.sendStickyBroadcast(newIntent);
1949 }
1950 }
1951 }
Eric Laurenta553c252009-07-17 12:17:14 -07001952 }
1953 }
1954 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08001955
1956 //==========================================================================================
1957 // AudioFocus
1958 //==========================================================================================
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07001959
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07001960 /* constant to identify focus stack entry that is used to hold the focus while the phone
1961 * is ringing or during a call
1962 */
1963 private final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
1964
Jean-Michel Trivi392a2bb2010-05-10 20:02:46 -07001965 private final static Object mAudioFocusLock = new Object();
1966
Jean-Michel Trivie73131a2010-06-14 09:53:30 -07001967 private final static Object mRingingLock = new Object();
1968
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07001969 private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
1970 @Override
1971 public void onCallStateChanged(int state, String incomingNumber) {
1972 if (state == TelephonyManager.CALL_STATE_RINGING) {
1973 //Log.v(TAG, " CALL_STATE_RINGING");
Jean-Michel Trivie73131a2010-06-14 09:53:30 -07001974 synchronized(mRingingLock) {
1975 mIsRinging = true;
1976 }
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07001977 int ringVolume = AudioService.this.getStreamVolume(AudioManager.STREAM_RING);
1978 if (ringVolume > 0) {
1979 requestAudioFocus(AudioManager.STREAM_RING,
1980 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
1981 null, null /* both allowed to be null only for this clientId */,
1982 IN_VOICE_COMM_FOCUS_ID /*clientId*/);
1983 }
1984 } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
1985 //Log.v(TAG, " CALL_STATE_OFFHOOK");
Jean-Michel Trivie73131a2010-06-14 09:53:30 -07001986 synchronized(mRingingLock) {
1987 mIsRinging = false;
1988 }
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07001989 requestAudioFocus(AudioManager.STREAM_RING,
1990 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
1991 null, null /* both allowed to be null only for this clientId */,
1992 IN_VOICE_COMM_FOCUS_ID /*clientId*/);
1993 } else if (state == TelephonyManager.CALL_STATE_IDLE) {
1994 //Log.v(TAG, " CALL_STATE_IDLE");
Jean-Michel Trivie73131a2010-06-14 09:53:30 -07001995 synchronized(mRingingLock) {
1996 mIsRinging = false;
1997 }
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07001998 abandonAudioFocus(null, IN_VOICE_COMM_FOCUS_ID);
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07001999 }
2000 }
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07002001 };
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07002002
2003 private void notifyTopOfAudioFocusStack() {
2004 // notify the top of the stack it gained focus
2005 if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2006 if (canReassignAudioFocus()) {
2007 try {
2008 mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
2009 AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId);
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07002010 } catch (RemoteException e) {
2011 Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e);
2012 e.printStackTrace();
2013 }
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07002014 }
2015 }
2016 }
2017
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002018 private static class FocusStackEntry {
2019 public int mStreamType = -1;// no stream type
2020 public boolean mIsTransportControlReceiver = false;
2021 public IAudioFocusDispatcher mFocusDispatcher = null;
2022 public IBinder mSourceRef = null;
2023 public String mClientId;
Jean-Michel Trivi078fd472010-03-18 16:51:04 -07002024 public int mFocusChangeType;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002025
2026 public FocusStackEntry() {
2027 }
2028
2029 public FocusStackEntry(int streamType, int duration, boolean isTransportControlReceiver,
2030 IAudioFocusDispatcher afl, IBinder source, String id) {
2031 mStreamType = streamType;
2032 mIsTransportControlReceiver = isTransportControlReceiver;
2033 mFocusDispatcher = afl;
2034 mSourceRef = source;
2035 mClientId = id;
Jean-Michel Trivi078fd472010-03-18 16:51:04 -07002036 mFocusChangeType = duration;
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002037 }
2038 }
2039
2040 private Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>();
2041
2042 /**
2043 * Helper function:
2044 * Display in the log the current entries in the audio focus stack
2045 */
2046 private void dumpFocusStack(PrintWriter pw) {
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07002047 pw.println("\nAudio Focus stack entries:");
Jean-Michel Trivi392a2bb2010-05-10 20:02:46 -07002048 synchronized(mAudioFocusLock) {
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002049 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2050 while(stackIterator.hasNext()) {
2051 FocusStackEntry fse = stackIterator.next();
2052 pw.println(" source:" + fse.mSourceRef + " -- client: " + fse.mClientId
Jean-Michel Trivi078fd472010-03-18 16:51:04 -07002053 + " -- duration: " +fse.mFocusChangeType);
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002054 }
2055 }
2056 }
2057
2058 /**
2059 * Helper function:
2060 * Remove a focus listener from the focus stack.
2061 * @param focusListenerToRemove the focus listener
2062 * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding
2063 * focus, notify the next item in the stack it gained focus.
2064 */
2065 private void removeFocusStackEntry(String clientToRemove, boolean signal) {
2066 // is the current top of the focus stack abandoning focus? (because of death or request)
2067 if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove))
2068 {
2069 //Log.i(TAG, " removeFocusStackEntry() removing top of stack");
2070 mFocusStack.pop();
2071 if (signal) {
2072 // notify the new top of the stack it gained focus
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07002073 notifyTopOfAudioFocusStack();
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002074 }
2075 } else {
2076 // focus is abandoned by a client that's not at the top of the stack,
2077 // no need to update focus.
2078 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2079 while(stackIterator.hasNext()) {
2080 FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2081 if(fse.mClientId.equals(clientToRemove)) {
2082 Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for "
2083 + fse.mClientId);
2084 mFocusStack.remove(fse);
2085 }
2086 }
2087 }
2088 }
2089
2090 /**
2091 * Helper function:
2092 * Remove focus listeners from the focus stack for a particular client.
2093 */
2094 private void removeFocusStackEntryForClient(IBinder cb) {
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07002095 // is the owner of the audio focus part of the client to remove?
2096 boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() &&
2097 mFocusStack.peek().mSourceRef.equals(cb);
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002098 Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator();
2099 while(stackIterator.hasNext()) {
2100 FocusStackEntry fse = (FocusStackEntry)stackIterator.next();
2101 if(fse.mSourceRef.equals(cb)) {
2102 Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for "
2103 + fse.mClientId);
2104 mFocusStack.remove(fse);
2105 }
2106 }
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07002107 if (isTopOfStackForClientToRemove) {
2108 // we removed an entry at the top of the stack:
2109 // notify the new top of the stack it gained focus.
2110 notifyTopOfAudioFocusStack();
2111 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002112 }
2113
2114 /**
2115 * Helper function:
2116 * Returns true if the system is in a state where the focus can be reevaluated, false otherwise.
2117 */
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002118 private boolean canReassignAudioFocus() {
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07002119 // focus requests are rejected during a phone call or when the phone is ringing
2120 // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus
2121 if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) {
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002122 return false;
2123 }
2124 return true;
2125 }
2126
2127 /**
2128 * Inner class to monitor audio focus client deaths, and remove them from the audio focus
2129 * stack if necessary.
2130 */
2131 private class AudioFocusDeathHandler implements IBinder.DeathRecipient {
2132 private IBinder mCb; // To be notified of client's death
2133
2134 AudioFocusDeathHandler(IBinder cb) {
2135 mCb = cb;
2136 }
2137
2138 public void binderDied() {
Jean-Michel Trivi392a2bb2010-05-10 20:02:46 -07002139 synchronized(mAudioFocusLock) {
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002140 Log.w(TAG, " AudioFocus audio focus client died");
2141 removeFocusStackEntryForClient(mCb);
2142 }
2143 }
2144
2145 public IBinder getBinder() {
2146 return mCb;
2147 }
2148 }
2149
2150
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002151 /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */
Jean-Michel Trivi078fd472010-03-18 16:51:04 -07002152 public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb,
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002153 IAudioFocusDispatcher fd, String clientId) {
2154 Log.i(TAG, " AudioFocus requestAudioFocus() from " + clientId);
2155 // the main stream type for the audio focus request is currently not used. It may
2156 // potentially be used to handle multiple stream type-dependent audio focuses.
2157
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07002158 // we need a valid binder callback for clients other than the AudioService's phone
2159 // state listener
2160 if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId) && ((cb == null) || !cb.pingBinder())) {
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002161 Log.i(TAG, " AudioFocus DOA client for requestAudioFocus(), exiting");
2162 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2163 }
2164
Jean-Michel Trivi392a2bb2010-05-10 20:02:46 -07002165 synchronized(mAudioFocusLock) {
2166 if (!canReassignAudioFocus()) {
2167 return AudioManager.AUDIOFOCUS_REQUEST_FAILED;
2168 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002169
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002170 if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) {
Jean-Michel Trivie5e1e872010-03-19 15:31:20 -07002171 // if focus is already owned by this client and the reason for acquiring the focus
2172 // hasn't changed, don't do anything
2173 if (mFocusStack.peek().mFocusChangeType == focusChangeHint) {
2174 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2175 }
2176 // the reason for the audio focus request has changed: remove the current top of
2177 // stack and respond as if we had a new focus owner
2178 mFocusStack.pop();
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002179 }
2180
2181 // notify current top of stack it is losing focus
2182 if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) {
2183 try {
2184 mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange(
Jean-Michel Trivi078fd472010-03-18 16:51:04 -07002185 -1 * focusChangeHint, // loss and gain codes are inverse of each other
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002186 mFocusStack.peek().mClientId);
2187 } catch (RemoteException e) {
2188 Log.e(TAG, " Failure to signal loss of focus due to "+ e);
2189 e.printStackTrace();
2190 }
2191 }
2192
Jean-Michel Trivi55d1bb32010-04-01 17:40:58 -07002193 // focus requester might already be somewhere below in the stack, remove it
2194 removeFocusStackEntry(clientId, false);
2195
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002196 // push focus requester at the top of the audio focus stack
Jean-Michel Trivi078fd472010-03-18 16:51:04 -07002197 mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, false, fd, cb,
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002198 clientId));
Jean-Michel Trivi392a2bb2010-05-10 20:02:46 -07002199 }//synchronized(mAudioFocusLock)
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002200
2201 // handle the potential premature death of the new holder of the focus
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07002202 // (premature death == death before abandoning focus) for a client which is not the
2203 // AudioService's phone state listener
2204 if (!IN_VOICE_COMM_FOCUS_ID.equals(clientId)) {
2205 // Register for client death notification
2206 AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb);
2207 try {
2208 cb.linkToDeath(afdh, 0);
2209 } catch (RemoteException e) {
2210 // client has already died!
2211 Log.w(TAG, "AudioFocus requestAudioFocus() could not link to "+cb+" binder death");
2212 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002213 }
2214
2215 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2216 }
2217
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002218 /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002219 public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) {
2220 Log.i(TAG, " AudioFocus abandonAudioFocus() from " + clientId);
Jean-Michel Trivi392a2bb2010-05-10 20:02:46 -07002221 try {
2222 // this will take care of notifying the new focus owner if needed
2223 synchronized(mAudioFocusLock) {
2224 removeFocusStackEntry(clientId, true);
2225 }
2226 } catch (java.util.ConcurrentModificationException cme) {
2227 // Catching this exception here is temporary. It is here just to prevent
2228 // a crash seen when the "Silent" notification is played. This is believed to be fixed
2229 // but this try catch block is left just to be safe.
2230 Log.e(TAG, "FATAL EXCEPTION AudioFocus abandonAudioFocus() caused " + cme);
2231 cme.printStackTrace();
Jean-Michel Trivi2930bb22010-04-09 19:27:58 -07002232 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002233
2234 return AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
2235 }
2236
2237
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002238 public void unregisterAudioFocusClient(String clientId) {
Jean-Michel Trivi392a2bb2010-05-10 20:02:46 -07002239 synchronized(mAudioFocusLock) {
Jean-Michel Trivi2930bb22010-04-09 19:27:58 -07002240 removeFocusStackEntry(clientId, false);
2241 }
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002242 }
2243
2244
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002245 //==========================================================================================
2246 // RemoteControl
2247 //==========================================================================================
2248 /**
2249 * Receiver for media button intents. Handles the dispatching of the media button event
2250 * to one of the registered listeners, or if there was none, resumes the intent broadcast
2251 * to the rest of the system.
2252 */
2253 private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
2254 @Override
2255 public void onReceive(Context context, Intent intent) {
2256 String action = intent.getAction();
2257 if (!Intent.ACTION_MEDIA_BUTTON.equals(action)) {
2258 return;
2259 }
2260 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
2261 if (event != null) {
2262 // if in a call or ringing, do not break the current phone app behavior
2263 // TODO modify this to let the phone app specifically get the RC focus
2264 // add modify the phone app to take advantage of the new API
Jean-Michel Trivie73131a2010-06-14 09:53:30 -07002265 synchronized(mRingingLock) {
2266 if (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL) ||
2267 (getMode() == AudioSystem.MODE_RINGTONE) ) {
2268 return;
2269 }
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002270 }
2271 synchronized(mRCStack) {
2272 if (!mRCStack.empty()) {
2273 // create a new intent specifically aimed at the current registered listener
2274 Intent targetedIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
2275 targetedIntent.putExtras(intent.getExtras());
2276 targetedIntent.setComponent(mRCStack.peek().mReceiverComponent);
2277 // trap the current broadcast
2278 abortBroadcast();
2279 //Log.v(TAG, " Sending intent" + targetedIntent);
2280 context.sendBroadcast(targetedIntent, null);
2281 }
2282 }
2283 }
2284 }
2285 }
2286
2287 private static class RemoteControlStackEntry {
2288 public ComponentName mReceiverComponent;// always non null
2289 // TODO implement registration expiration?
2290 //public int mRegistrationTime;
2291
2292 public RemoteControlStackEntry() {
2293 }
2294
2295 public RemoteControlStackEntry(ComponentName r) {
2296 mReceiverComponent = r;
2297 }
2298 }
2299
2300 private Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>();
2301
2302 /**
2303 * Helper function:
2304 * Display in the log the current entries in the remote control focus stack
2305 */
2306 private void dumpRCStack(PrintWriter pw) {
Jean-Michel Trivib4bccb62010-04-20 14:56:34 -07002307 pw.println("\nRemote Control stack entries:");
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002308 synchronized(mRCStack) {
2309 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2310 while(stackIterator.hasNext()) {
2311 RemoteControlStackEntry fse = stackIterator.next();
2312 pw.println(" receiver:" + fse.mReceiverComponent);
2313 }
2314 }
2315 }
2316
2317 /**
2318 * Helper function:
2319 * Set the new remote control receiver at the top of the RC focus stack
2320 */
2321 private void pushMediaButtonReceiver(ComponentName newReceiver) {
2322 // already at top of stack?
2323 if (!mRCStack.empty() && mRCStack.peek().mReceiverComponent.equals(newReceiver)) {
2324 return;
2325 }
2326 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2327 while(stackIterator.hasNext()) {
2328 RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
2329 if(rcse.mReceiverComponent.equals(newReceiver)) {
2330 mRCStack.remove(rcse);
2331 break;
2332 }
2333 }
2334 mRCStack.push(new RemoteControlStackEntry(newReceiver));
2335 }
2336
2337 /**
2338 * Helper function:
2339 * Remove the remote control receiver from the RC focus stack
2340 */
2341 private void removeMediaButtonReceiver(ComponentName newReceiver) {
2342 Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
2343 while(stackIterator.hasNext()) {
2344 RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
2345 if(rcse.mReceiverComponent.equals(newReceiver)) {
2346 mRCStack.remove(rcse);
2347 break;
2348 }
2349 }
2350 }
2351
2352
2353 /** see AudioManager.registerMediaButtonEventReceiver(ComponentName eventReceiver) */
2354 public void registerMediaButtonEventReceiver(ComponentName eventReceiver) {
2355 Log.i(TAG, " Remote Control registerMediaButtonEventReceiver() for " + eventReceiver);
2356
2357 synchronized(mRCStack) {
2358 pushMediaButtonReceiver(eventReceiver);
2359 }
2360 }
2361
2362 /** see AudioManager.unregisterMediaButtonEventReceiver(ComponentName eventReceiver) */
2363 public void unregisterMediaButtonEventReceiver(ComponentName eventReceiver) {
Jean-Michel Trivi55d1bb32010-04-01 17:40:58 -07002364 Log.i(TAG, " Remote Control unregisterMediaButtonEventReceiver() for " + eventReceiver);
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002365
2366 synchronized(mRCStack) {
2367 removeMediaButtonReceiver(eventReceiver);
2368 }
2369 }
2370
2371
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002372 @Override
2373 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002374 // TODO probably a lot more to do here than just the audio focus and remote control stacks
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002375 dumpFocusStack(pw);
Jean-Michel Trivid327f212010-03-16 21:44:33 -07002376 dumpRCStack(pw);
Jean-Michel Trivid5176cf2010-01-28 11:56:42 -08002377 }
2378
2379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380}