react-native-background-timer inconsistently works on Android for recording audio

Viewed 437

I am using BackgroundTimer from react-native-background-timer in a React native project for Android.

I want a user to be able to record audio after a set duration (e.g. record for 5 minutes after 30 minutes).

The issue I have is that it works "sometimes". It seems the OS is often killing the process - especially if the time to execute is longer.

Code extract:

import BackgroundTimer from 'react-native-background-timer';
...

// Start a timer that runs once after X milliseconds
const timeout1 = BackgroundTimer.setTimeout(() => {

    // Should work when when app is the the background
    this.onStartRecord();

    const timeout2 = BackgroundTimer.setTimeout(() => {
        this.onStopRecord();
        BackgroundTimer.clearTimeout(timeout2);
    }, millisRecording);

    // Clear first timeout
    BackgroundTimer.clearTimeout(timeout1);

}, millisUntilRecordMoment);

Thes rest of the code is here: https://github.com/bentaly/listen/blob/master/App.tsx

I have also tried building this in Expo previously which didn't work.

Is there anyway to guarantee this operation will work?

1 Answers

You will have around ~40 seconds to call your function and call the completion handler in the background state or phone is in the sleep state.

If you don't finish it on time, iOS will kill your app. If you don't obey the rules, iOS will give you less chances to wake up. For more detailed usage of Background Modes, you may check following tutorial

It is due to app developers abusing this mechanism, killing their customers' device battery.

Note: Watchdog Timeout is ~40 sec.

Related