Music Sleep Timer function: I need the timer to run out onApplicationPause.

Hi All,
I could really use some help. I’m updating an android app i’ve made and I want to add a sleep timer function for users to fall asleep to audio.
I’ve got my audio able to run in background using Android Native Audio plugin.
But I just can’t get the timer to work out of focus or on pause. I don’t need to keep track of the time I just need it to run out. I’ve tried a few variations of co-routines but still getting nowhere.
Here is my working script:

using UnityEngine;
using UnityEngine.UI;

public class CountdownTimer : MonoBehaviour
{
    public float timeRemaining = 60;
    public Slider slider;
    public Text TimerText;
    public Text RunningTimer;
    public bool timerIsRunning;


    private void Start()
    {
        timerIsRunning = false;
    }
    void Update()
    {

        if (timerIsRunning)
        {
            slider.value = timeRemaining;
            if (timeRemaining > 0)
            {
                timeRemaining -= Time.deltaTime;
                DisplayTime(timeRemaining);
            }
            else
            {
                timeRemaining = 0;
                timerIsRunning = false;
                GameObject.Find("AUDIOPANEL").GetComponent<TestAudioManager>().StopAudio();
            }
        }
    }
    //I'm not sure what to do with the update method when i'm trying to use onapplicationpause/focus....please help.
    public void DisplayTime(float DisplayTime)
    {
        DisplayTime += 1;

        float minutes = Mathf.FloorToInt(DisplayTime / 60);
        float seconds = Mathf.FloorToInt(DisplayTime % 60);

        TimerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
        RunningTimer.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }

    public void SetTime(float value)
    {
        string sliderMessage = Mathf.Round(slider.value / 60) + ":00";
        TimerText.text = sliderMessage;
        RunningTimer.text = sliderMessage;
    }
    public void StartTimer()
    {
        timerIsRunning = true;
        timeRemaining = slider.value;
    }

    public void StopTimer()
    {
        timerIsRunning = false;
    }
}

Kind of like the solution above, I’m pretty sure you need to implement some sort of Android-side timer that persists and can do stuff while your app isn’t in focus. I don’t have direct experience with these background modes in Android but obviously they are possible.

1 Like

I was afraid of that :frowning: I had a hard enough time getting the Audio to work. *sigh.
Thanks for your quick reply :slight_smile:

For posterity: This asset gave me an elegant solution -

Thank you @Vuopaja for your assistance getting it implemented.

1 Like