1 /* 2 * Copyright (C) 2008 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 17 package com.android.server; 18 19 import android.content.Context; 20 import android.media.AudioManager; 21 import android.media.MediaPlayer; 22 import android.media.MediaPlayer.OnCompletionListener; 23 import android.net.Uri; 24 import android.os.Handler; 25 import android.os.Looper; 26 import android.os.Message; 27 import android.os.PowerManager; 28 import android.os.SystemClock; 29 import android.util.Log; 30 31 import java.io.IOException; 32 import java.lang.IllegalStateException; 33 import java.lang.Thread; 34 import java.util.LinkedList; 35 36 /** 37 * @hide 38 * This class is provides the same interface and functionality as android.media.AsyncPlayer 39 * with the following differences: 40 * - whenever audio is played, audio focus is requested, 41 * - whenever audio playback is stopped or the playback completed, audio focus is abandoned. 42 */ 43 public class NotificationPlayer implements OnCompletionListener { 44 private static final int PLAY = 1; 45 private static final int STOP = 2; 46 private static final boolean mDebug = false; 47 48 private static final class Command { 49 int code; 50 Context context; 51 Uri uri; 52 boolean looping; 53 int stream; 54 long requestTime; 55 56 public String toString() { 57 return "{ code=" + code + " looping=" + looping + " stream=" + stream 58 + " uri=" + uri + " }"; 59 } 60 } 61 62 private LinkedList<Command> mCmdQueue = new LinkedList(); 63 64 private Looper mLooper; 65 66 /* 67 * Besides the use of audio focus, the only implementation difference between AsyncPlayer and 68 * NotificationPlayer resides in the creation of the MediaPlayer. For the completion callback, 69 * OnCompletionListener, to be called at the end of the playback, the MediaPlayer needs to 70 * be created with a looper running so its event handler is not null. 71 */ 72 private final class CreationAndCompletionThread extends Thread { 73 public Command mCmd; 74 public CreationAndCompletionThread(Command cmd) { 75 super(); 76 mCmd = cmd; 77 } 78 79 public void run() { 80 Looper.prepare(); 81 mLooper = Looper.myLooper(); 82 synchronized(this) { 83 AudioManager audioManager = 84 (AudioManager) mCmd.context.getSystemService(Context.AUDIO_SERVICE); 85 try { 86 MediaPlayer player = new MediaPlayer(); 87 player.setAudioStreamType(mCmd.stream); 88 player.setDataSource(mCmd.context, mCmd.uri); 89 player.setLooping(mCmd.looping); 90 player.prepare(); 91 if ((mCmd.uri != null) && (mCmd.uri.getEncodedPath() != null) 92 && (mCmd.uri.getEncodedPath().length() > 0)) { 93 if (mCmd.looping) { 94 audioManager.requestAudioFocus(null, mCmd.stream, 95 AudioManager.AUDIOFOCUS_GAIN); 96 } else { 97 audioManager.requestAudioFocus(null, mCmd.stream, 98 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK); 99 } 100 } 101 player.setOnCompletionListener(NotificationPlayer.this); 102 player.start(); 103 if (mPlayer != null) { 104 mPlayer.release(); 105 } 106 mPlayer = player; 107 } 108 catch (Exception e) { 109 Log.w(mTag, "error loading sound for " + mCmd.uri, e); 110 } 111 mAudioManager = audioManager; 112 this.notify(); 113 } 114 Looper.loop(); 115 } 116 }; 117 118 private void startSound(Command cmd) { 119 // Preparing can be slow, so if there is something else 120 // is playing, let it continue until we're done, so there 121 // is less of a glitch. 122 try { 123 if (mDebug) Log.d(mTag, "Starting playback"); 124 //----------------------------------- 125 // This is were we deviate from the AsyncPlayer implementation and create the 126 // MediaPlayer in a new thread with which we're synchronized 127 synchronized(mCompletionHandlingLock) { 128 // if another sound was already playing, it doesn't matter we won't get notified 129 // of the completion, since only the completion notification of the last sound 130 // matters 131 if((mLooper != null) 132 && (mLooper.getThread().getState() != Thread.State.TERMINATED)) { 133 mLooper.quit(); 134 } 135 mCompletionThread = new CreationAndCompletionThread(cmd); 136 synchronized(mCompletionThread) { 137 mCompletionThread.start(); 138 mCompletionThread.wait(); 139 } 140 } 141 //----------------------------------- 142 143 long delay = SystemClock.uptimeMillis() - cmd.requestTime; 144 if (delay > 1000) { 145 Log.w(mTag, "Notification sound delayed by " + delay + "msecs"); 146 } 147 } 148 catch (Exception e) { 149 Log.w(mTag, "error loading sound for " + cmd.uri, e); 150 } 151 } 152 153 private final class CmdThread extends java.lang.Thread { 154 CmdThread() { 155 super("NotificationPlayer-" + mTag); 156 } 157 158 public void run() { 159 while (true) { 160 Command cmd = null; 161 162 synchronized (mCmdQueue) { 163 if (mDebug) Log.d(mTag, "RemoveFirst"); 164 cmd = mCmdQueue.removeFirst(); 165 } 166 167 switch (cmd.code) { 168 case PLAY: 169 if (mDebug) Log.d(mTag, "PLAY"); 170 startSound(cmd); 171 break; 172 case STOP: 173 if (mDebug) Log.d(mTag, "STOP"); 174 if (mPlayer != null) { 175 long delay = SystemClock.uptimeMillis() - cmd.requestTime; 176 if (delay > 1000) { 177 Log.w(mTag, "Notification stop delayed by " + delay + "msecs"); 178 } 179 mPlayer.stop(); 180 mPlayer.release(); 181 mPlayer = null; 182 mAudioManager.abandonAudioFocus(null); 183 mAudioManager = null; 184 if((mLooper != null) 185 && (mLooper.getThread().getState() != Thread.State.TERMINATED)) { 186 mLooper.quit(); 187 } 188 } else { 189 Log.w(mTag, "STOP command without a player"); 190 } 191 break; 192 } 193 194 synchronized (mCmdQueue) { 195 if (mCmdQueue.size() == 0) { 196 // nothing left to do, quit 197 // doing this check after we're done prevents the case where they 198 // added it during the operation from spawning two threads and 199 // trying to do them in parallel. 200 mThread = null; 201 releaseWakeLock(); 202 return; 203 } 204 } 205 } 206 } 207 } 208 209 public void onCompletion(MediaPlayer mp) { 210 if (mAudioManager != null) { 211 mAudioManager.abandonAudioFocus(null); 212 } 213 // if there are no more sounds to play, end the Looper to listen for media completion 214 synchronized (mCmdQueue) { 215 if (mCmdQueue.size() == 0) { 216 synchronized(mCompletionHandlingLock) { 217 if(mLooper != null) { 218 mLooper.quit(); 219 } 220 mCompletionThread = null; 221 } 222 } 223 } 224 } 225 226 private String mTag; 227 private CmdThread mThread; 228 private CreationAndCompletionThread mCompletionThread; 229 private final Object mCompletionHandlingLock = new Object(); 230 private MediaPlayer mPlayer; 231 private PowerManager.WakeLock mWakeLock; 232 private AudioManager mAudioManager; 233 234 // The current state according to the caller. Reality lags behind 235 // because of the asynchronous nature of this class. 236 private int mState = STOP; 237 238 /** 239 * Construct a NotificationPlayer object. 240 * 241 * @param tag a string to use for debugging 242 */ 243 public NotificationPlayer(String tag) { 244 if (tag != null) { 245 mTag = tag; 246 } else { 247 mTag = "NotificationPlayer"; 248 } 249 } 250 251 /** 252 * Start playing the sound. It will actually start playing at some 253 * point in the future. There are no guarantees about latency here. 254 * Calling this before another audio file is done playing will stop 255 * that one and start the new one. 256 * 257 * @param context Your application's context. 258 * @param uri The URI to play. (see {@link MediaPlayer#setDataSource(Context, Uri)}) 259 * @param looping Whether the audio should loop forever. 260 * (see {@link MediaPlayer#setLooping(boolean)}) 261 * @param stream the AudioStream to use. 262 * (see {@link MediaPlayer#setAudioStreamType(int)}) 263 */ 264 public void play(Context context, Uri uri, boolean looping, int stream) { 265 Command cmd = new Command(); 266 cmd.requestTime = SystemClock.uptimeMillis(); 267 cmd.code = PLAY; 268 cmd.context = context; 269 cmd.uri = uri; 270 cmd.looping = looping; 271 cmd.stream = stream; 272 synchronized (mCmdQueue) { 273 enqueueLocked(cmd); 274 mState = PLAY; 275 } 276 } 277 278 /** 279 * Stop a previously played sound. It can't be played again or unpaused 280 * at this point. Calling this multiple times has no ill effects. 281 */ 282 public void stop() { 283 synchronized (mCmdQueue) { 284 // This check allows stop to be called multiple times without starting 285 // a thread that ends up doing nothing. 286 if (mState != STOP) { 287 Command cmd = new Command(); 288 cmd.requestTime = SystemClock.uptimeMillis(); 289 cmd.code = STOP; 290 enqueueLocked(cmd); 291 mState = STOP; 292 } 293 } 294 } 295 296 private void enqueueLocked(Command cmd) { 297 mCmdQueue.add(cmd); 298 if (mThread == null) { 299 acquireWakeLock(); 300 mThread = new CmdThread(); 301 mThread.start(); 302 } 303 } 304 305 /** 306 * We want to hold a wake lock while we do the prepare and play. The stop probably is 307 * optional, but it won't hurt to have it too. The problem is that if you start a sound 308 * while you're holding a wake lock (e.g. an alarm starting a notification), you want the 309 * sound to play, but if the CPU turns off before mThread gets to work, it won't. The 310 * simplest way to deal with this is to make it so there is a wake lock held while the 311 * thread is starting or running. You're going to need the WAKE_LOCK permission if you're 312 * going to call this. 313 * 314 * This must be called before the first time play is called. 315 * 316 * @hide 317 */ 318 public void setUsesWakeLock(Context context) { 319 if (mWakeLock != null || mThread != null) { 320 // if either of these has happened, we've already played something. 321 // and our releases will be out of sync. 322 throw new RuntimeException("assertion failed mWakeLock=" + mWakeLock 323 + " mThread=" + mThread); 324 } 325 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 326 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mTag); 327 } 328 329 private void acquireWakeLock() { 330 if (mWakeLock != null) { 331 mWakeLock.acquire(); 332 } 333 } 334 335 private void releaseWakeLock() { 336 if (mWakeLock != null) { 337 mWakeLock.release(); 338 } 339 } 340 } 341 342