jamesisaac / react-native-background-task

Periodic background tasks for React Native apps, cross-platform (iOS and Android), which run even when the app is closed.
MIT License
1.1k stars 110 forks source link

The task written under register() method never gets called #3

Closed ashishd751 closed 7 years ago

ashishd751 commented 7 years ago

Somehow the task written under the register() method never gets called ! Below is my code, please let me know what i'm doing wrong.

` <TouchableNativeFeedback onPress={() => { //this.interval = setInterval(this.tick(), 1000);

            BackgroundTask.register(() => {
              console.log('Hello from a background task')
              BackgroundTask.finish()
            },{
              period : 1
            })

this.setState({ timerStarted : true }) } } background={TouchableNativeFeedback.SelectableBackground()}>

{!this.state.timerStarted && Start}
      </TouchableNativeFeedback>

`

jamesisaac commented 7 years ago

The task should be registered at the very top level of your JS file. If you want to determine whether a button has been pressed, you'll have to use something like AsyncStorage to communicate between the main app and the background task.

jamesisaac commented 7 years ago

I'm working on a new API now (PR #5) which will allow you to define the task separately from scheduling it. So while you'll still need to define the function body outside your components, you can schedule it in an onPress as you were trying to do above.