DeskClock: Ensure ringtone is playing when starting the crescendo effect (#4)

Signed-off-by: iusmac <iusico.maxim@libero.it>
Signed-off-by: Pranav Temkar <pranavtemkar@gmail.com>
Signed-off-by: Jis G Jacob <studiokeys@blissroms.org>
diff --git a/src/com/android/deskclock/AsyncRingtonePlayer.java b/src/com/android/deskclock/AsyncRingtonePlayer.java
index 02cad6f..9c05181 100644
--- a/src/com/android/deskclock/AsyncRingtonePlayer.java
+++ b/src/com/android/deskclock/AsyncRingtonePlayer.java
@@ -255,6 +255,9 @@
         /** The current ringtone. Only used by the ringtone thread. */
         private Ringtone mRingtone;
 
+        /** The ringtone playback attempts counter. */
+        private int mRingtonePlayRetries = 0;
+
         /** The duration over which to increase the volume. */
         private long mCrescendoDuration = 0;
 
@@ -387,13 +390,35 @@
         public boolean adjustVolume() {
             checkAsyncRingtonePlayerThread();
 
-            // If ringtone is absent or not playing, ignore volume adjustment.
-            if (mRingtone == null || !mRingtone.isPlaying()) {
+            // If ringtone is absent, ignore volume adjustment.
+            if (mRingtone == null) {
                 mCrescendoDuration = 0;
                 mCrescendoStopTime = 0;
                 return false;
             }
 
+            // If ringtone is not playing, to avoid being muted forever recheck
+            // to ensure reliability.
+            if (!mRingtone.isPlaying()) {
+                if (mRingtonePlayRetries < 10) {
+                    mRingtonePlayRetries++;
+                    // Reuse the crescendo messaging looper to return here
+                    // again.
+                    return true;
+                }
+
+                mRingtonePlayRetries = 0;
+                mCrescendoDuration = 0;
+                mCrescendoStopTime = 0;
+                return false;
+            }
+
+            if (mRingtonePlayRetries > 0) {
+                mRingtonePlayRetries = 0;
+                // Compute again the time at which the crescendo will stop.
+                mCrescendoStopTime = Utils.now() + mCrescendoDuration;
+            }
+
             // If the crescendo is complete set the volume to the maximum; we're done.
             final long currentTime = Utils.now();
             if (currentTime > mCrescendoStopTime) {