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