无法让后台任务在React-Native

时间:2019-10-02 11:31:31

标签: android ios react-native background-process

我需要经常写入文本文件,比如说在iOS和android中,使用react-native将时间戳记写入文件。我在以下库的帮助下编写了一个应用程序。在android上,该应用程序运行正常,但在 iOS 上无法正常运行。

我尝试使用这些库:

  1. react-native-background-task
  2. react-native-background-fetch
  3. react-native-background-queue + react-native-background-task

但它们都无法正常工作

  1. 带有react-native-background-task:文件随机写入5-6 一天或更短的时间
  2. with react-native-background-fetch:随机写入文件 每天少于3-4次
  3. react-native-background-queue + react-native-background-task: 文件根本没有写!

请告诉我这些行为是否正常,否则,我在做什么错??

任何帮助将不胜感激。

这是我的代码:

为了使用 react-native-background-task

import React from 'react'
import Mytest from './test';
import BackgroundTask from 'react-native-background-task'
import {
    Text,
    View,
  } from 'react-native';

BackgroundTask.define(() => {
  console.log('Hello from a background task')
  Mytest.writeFiles()
  BackgroundTask.finish()
})

export default class MyApp extends React.Component {

  componentDidMount() {
    BackgroundTask.schedule()
  }

  render() {
    return(
     <View>
      <Text>Hello world</Text>
    </View>)
  }

}

为了使用 react-native-background-fetch

import React, { Component } from 'react';
import {
    Text,
    View,
    StyleSheet
  } from 'react-native';
import BackgroundFetch from "react-native-background-fetch";

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/fetch.txt';
var count = 0

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      date: '',
    }
  }

  componentDidMount() {
    BackgroundFetch.configure({
      stopOnTerminate: false,
      startOnBoot: true,
      requiredNetworkType: BackgroundFetch.NETWORK_TYPE_NONE,
      requiresCharging: false,      // Default
      requiresDeviceIdle: false,    // Default
      requiresBatteryNotLow: false, // Default
      requiresStorageNotLow: false  // Default
    }, () => {
      console.log("[js] Received background-fetch event");
      this.writeFiles()
      BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
    }, (error) => {
      console.log("[js] RNBackgroundFetch failed to start");
    });

    BackgroundFetch.status((status) => {
      switch(status) {
        case BackgroundFetch.STATUS_RESTRICTED:
          console.log("BackgroundFetch restricted");
          break;
        case BackgroundFetch.STATUS_DENIED:
          console.log("BackgroundFetch denied");
          break;
        case BackgroundFetch.STATUS_AVAILABLE:
          console.log("BackgroundFetch is enabled");
          break;
      }
    });
  }

  render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to React Native!
            </Text>
          </View>
        );
      }


  getDate() {
    var that = this;
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    that.setState({
      date:
        date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec,
    });
  }


writeFiles = async () => {
  this.getDate()
    try {
      for(let i = 0; i < 1; i++){
        count = count + 1;
        console.log(count);
        RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + this.state.date , 'utf8')
        .then((success) => {
        })
      }
    }catch (err) {
      console.warn("error", err);
    } 
}          

};

为了使用 react-native-background-queue + react-native-background-task

import React, { Component } from 'react';
import Mytest from './test';
import BackgroundTask from 'react-native-background-task'
import {Platform,...} from 'react-native';
import queueFactory from 'react-native-queue';

BackgroundTask.define(async () => {
  queue = await queueFactory();
  queue.addWorker('background-example', async (id, payload) => {
  if (payload.name == 'sima') {
     Mytest.writeFiles()
     console.log('Hello from a background task ')}
  });
  await queue.start(20000); 
  BackgroundTask.finish();
});

export default class App extends Component<{}> {

  constructor(props) {
    super(props);

    this.state = {
      queue: null,
      data: null,
    };

    this.init();

  }

  async init() {
    const queue = await queueFactory();
    queue.addWorker('background-example', async (id, payload) => {
    });

    this.setState({
      queue
    });

  }

  componentDidMount() {
    BackgroundTask.schedule(); 
  }

  makeJob(jobName, payload = {}) {
    console.log('job is created but will not execute until the above OS background task runs in ~15 min');
    this.state.queue.createJob(jobName, payload, {
     timeout: 5000
    }, false); 
  }


  render() {
    let output = 'No data loaded from OS background task yet.';
    if (this.state.data) {
      output = JSON.stringify(this.state.data);
    }

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text>Click buttons below to add OS background task jobs.</Text>
        <Text>Then Close App (task will not fire if app is in focus).</Text>
        <Text>Job will exec in ~15 min in OS background.</Text>
        {this.state.queue && <Button title={"Press To Queue sima Job"} onPress={ () => { this.makeJob('background-example', { name: 'sima' }) } } /> }
        {this.state.queue && <Button title={"Press To Queue another Job"} onPress={ () => { this.makeJob('background-example', { name: 'simsim' }) } } /> }
        <Text>{output}</Text>
      </View>
    );

  }


}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

这是test.js:

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/test.txt';
var count = 0;

const Mytest = {

  writeFiles: () => {
    var that = this;
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    var date = date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec

      try {
        for(let i = 0; i < 1; i++){
          count = count + 1;
          console.log(count);
          RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + date , 'utf8')
          .then((success) => {
            console.log('FILE WRITTEN!');
          })
        }
      }catch (err) {
        console.warn("error", err);
      } 
  }
  }
  export default Mytest;

0 个答案:

没有答案