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