React Native: Is there a callback function for whe

2020-07-09 03:02发布

I have a setInterval that keeps running even when you close (not quit) the app. I would like to call a function when my app is closed or the device is put to sleep so that it clears the setInterval.

2条回答
Fickle 薄情
2楼-- · 2020-07-09 03:31

itinance was close. The answer is actually to use

AppState.addEventListener('change', state => {
  if (state === 'active') {
    // do this
  } else if (state === 'background') {
    // do that
  } else if (state === 'inactive') {
    // do that other thing
  }
});
查看更多
别忘想泡老子
3楼-- · 2020-07-09 03:40

AppState is your friend! Have a look at the documentation of AppState.

So in your component, where the setTimeout exists, just require AppState and add an event listener like this:

AppState.addEventListener('background', this.handlePutAppToBackground);
AppState.addEventListener('inactive', this.handlePutAppToBackground);

handlePutAppToBackground() would be now a method in your component, where you would call clearTimeout(...)

查看更多
登录 后发表回答