React Native - timer progress with screen off

Viewed 1270

I need to sound a bell when the timer has finished. I am running a timer with setInterval(). It works fine when the screen is on, and the app is keeping the screen from turning off automatically. However, if the user turns of the screen using the power button, the timer will just stop ticking after 3 minutes, and will not trigger the sound. This is due to Android sleep mode and no wake-lock, I assume . If I turn the screen on again, it will resume ticking. How can I enable a wake-lock?

I have tried:

  • react-native-background-timer - helps to keep ticking if the app is in the background, but not with the screen off
  • react-native-video playing some audio file. The audio keeps playing with screen off, but the timer still stops when the screen is off for 3 min

Here is a (working) sample function code in my timer class:

play = () => {
    if (this.timeLeft != 0) {
      this.paused = false
      this.running = BackgroundTimer.setInterval(() => {
        if (!this.paused) {
          this.timePassed++
          this.timeLeft = this.duration - this.timePassed     
        }
        if(this.timeLeft <= 0) {
          BackgroundTimer.clearInterval(this.running)
          this.playBell()
        }
      }, 1000)
    } else {
      this.stopped = true
    }
  }

How can I ensure the code runs with a wake-lock?

1 Answers

Not wanting to mess with native code, I did the following:

react-native-video has support for screen-off playback with playInBackground={true}, and it's onProgress, onEnd etc keep working with a screen turned off, so I run all timer-ticking code in those callbacks. If you are not using a timer to play back video/audio, you can still use react-native-video by playing a small silent audio file on repeat.

Related