Reputation: 1613
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:
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?
Upvotes: 2
Views: 1823
Reputation: 1613
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.
Upvotes: 1