即使在React Native中重启设备也如何运行后台任务?

时间:2018-12-16 22:02:40

标签: react-native queue background-task

我想制作一个可以在后台从服务器获取数据的应用程序。我使用react-native-queue,但是重新启动设备后无法正常工作。有什么解决办法吗?

export default class Stores extends Component<{}> {

constructor(props){
    super(props);
    this.state = { nodes: [], isFetching: false, mailListener:{connecting:false},queue: null};
  }

componentDidMount(){
    this.init();
  }

async init() {
    const queue = await queueFactory();
    const present = this;

    queue.addWorker('listener', async (id, payload) => {

      //my jobs here

      await new Promise((resolve) => {
        setTimeout(async () => {
          // Keep creating these jobs until counter reaches 3.
            queue.createJob('listener');
          resolve();
        }, 3000);
      });
    });

    queue.createJob('listener');

    queue.start();

    // Attach initialized queue to state.
    this.setState({
      queue
    });
  }

}

1 个答案:

答案 0 :(得分:0)

您可以使用react-nativeo-threads之类的方法,但是没有什么可以阻止用户关闭您的应用程序。每当您重新启动设备时,也会发生这种情况。关闭应用程序时无需提取内容,那么只要打开应用程序就可以进行获取,以便用户始终看到最新信息? 我的应用程序中有类似的任务,这是我的一些其他建议:

-让用户自己刷新数据(我使用拉动刷新列表)

-使后端发出事件,您的应用程序可以监听事件,这样您就无需同步

-后台同步任务不能以少于20分钟的时间间隔完成。如果您这样做会因为电池电量耗尽而将其从应用商店中拒绝。

祝你好运!

相关问题