2

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?

2
  • Were you able to solve this ? I have the same problem with background-timer. Commented Jul 27, 2020 at 14:12
  • Kind of. I posted an answer Commented Jul 27, 2020 at 14:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.