import React from 'react'; import format from 'date-format'; import { NavigationEvents } from 'react-navigation'; import * as TaskManager from 'expo-task-manager'; import * as BackgroundFetch from 'expo-background-fetch'; import { AppState, AsyncStorage, StyleSheet, Text, View, AppStateStatus } from 'react-native'; import Button from '../components/Button'; const BACKGROUND_FETCH_TASK = 'background-fetch'; const LAST_FETCH_DATE_KEY = 'background-fetch-date'; interface State { fetchDate?: Date; status?: BackgroundFetch.Status | null; isRegistered: boolean; } export default class BackgroundFetchScreen extends React.Component<{}, State> { static navigationOptions = { title: 'Background Fetch', }; readonly state: State = { isRegistered: false, }; componentDidMount() { AppState.addEventListener('change', this.handleAppStateChange); } componentWillUnmount() { AppState.removeEventListener('change', this.handleAppStateChange); } didFocus = () => { this.refreshLastFetchDateAsync(); this.checkStatusAsync(); } handleAppStateChange = (nextAppState: AppStateStatus) => { if (nextAppState === 'active') { this.refreshLastFetchDateAsync(); } } async refreshLastFetchDateAsync() { const lastFetchDateStr = await AsyncStorage.getItem(LAST_FETCH_DATE_KEY); if (lastFetchDateStr) { this.setState({ fetchDate: new Date(+lastFetchDateStr) }); } } async checkStatusAsync() { const status = await BackgroundFetch.getStatusAsync(); const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_FETCH_TASK); this.setState({ status, isRegistered }); } toggle = async () => { if (this.state.isRegistered) { await BackgroundFetch.unregisterTaskAsync(BACKGROUND_FETCH_TASK); } else { await BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, { minimumInterval: 60, // 1 minute stopOnTerminate: false, startOnBoot: true, }); } this.setState({ isRegistered: !this.state.isRegistered }); } renderText() { if (!this.state.fetchDate) { return There was no BackgroundFetch call yet.; } return ( Last background fetch was invoked at: {format('yyyy-MM-dd hh:mm:ss:SSS', this.state.fetchDate)} ); } render() { return ( Background fetch status:{' '} {this.state.status ? BackgroundFetch.Status[this.state.status] : null} {this.renderText()}