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