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