This is a React Native Foreground Service example app. The
react-native init command was used to create the initial project and the react-native-create-library tool was used as a start for the foreground service.
- Uses react-native-background-job
- Simple setInterval
- option to start Foreground Service
Action Performed at Each 10 Second Interval
- Writes timestamp to Redux store
- Calls bluetoothScan from react-native-ble-plx for devices
I wrote this example because I'd like to run a background timer at a regular interval and a Foreground Service sounds like the correct approach for Android. On further reading it sounds like this will not work afterall.
Another approach would be to setup a native timer using the Android AlarmManager and on every interval send an event to JS as described here.
Some have suggested react-native-background-timer or react-native-background-job but these have other limitations. The react-native-background-job package tried using a Foreground Service and found it to be unstable so it was removed from the 2.x version.
The app starts a loop that runs every 10 seconds and displays the elapsed time (should be 10 seconds). The loop pushes a timestamp into the Redux store which is read and displayed by the main component. There's a switch at the top of the screen to enable/disable the foreground service. You'll see the Android Foreground Service notification confirming that it is running.
Based on posts regarding Foreground Services, I would expect the 10 second timestamps to be posted to the component even when the app is not in focus but I have not found this to be the case. Whether the foreground service is running or not, when you switch away from the app, the 10 second updates stop.
Try it Out!
git clone https://github.com/rgstephens/RNForegroundExample.git yarn npm start react-native run-android