我正在构建一个应用程序,用户必须在其中输入时间,并且每天都会在该特定时间触发一个简单的功能。当应用程序处于前台时,可以处理此问题。但是当应用程序处于关闭状态时。那没有用,我找不到执行该功能的有效方法。
添加了最小代码段
async componentDidMount() {
this.loadaccountDetail();
this.interval = setInterval( () => this.setState(prevState => ({ timer: prevState.timer - 1 }) ),1000);
SplashScreen.hide();
}
componentDidUpdate() {
if (this.state.timer === 1) {
clearInterval(this.interval);
}
}
async loadaccountDetail() {
let userId = await AsyncStorage.getItem("id");
const user = JSON.parse(userId);
this.setState({ user: user });
try {
var that = this;
var date = moment().format("YYYY-MM-DD HH:mm:ss")
var expirydate = this.props.matchapprovedate; //You can set your own date-time
var diffr = moment.duration(moment(expirydate).diff(moment(date)));
var hours = parseInt(diffr.asHours());
var minutes = parseInt(diffr.minutes());
var seconds = parseInt(diffr.seconds());
var d = hours * 60 * 60 + minutes * 60 + seconds;
//converting in seconds
that.setState({ totalDuration: d });
if(d == 10){
this.abortDate()
}
else{
console.log('not now')
}
this.setState({ data: !this.state.data });
}
catch (err) {
console.log("catch:" + err);
}
}
abortDate() {
ApiService.abortDate({ userid: this.props.userid })
.then(async response => {
if (response.status == 1) {
NavigationService.navigate("news");
ToastService.showToast("You canceled the date sucessfully","error",3000);
}
else {
ToastService.showToast("Not able to cancel date", "error", 3000);
}
})
.catch(err => {
console.log(err)
});
}
render() {
const { matchapprovedate } = this.props;
const { userid } = this.props;
return (
<View style={{flex:1}}>
<CountDown
digitStyle={{ backgroundColor: "transparent" }}
digitTxtStyle={{ padding: 0, color: "#998299"}}
timeLabelStyle={{ color: "#998299"}}
until={this.state.totalDuration}
//duration of countdown in seconds
timeToShow={["H", "M", "S"]}
timeLabels={{ h: "HH", m: "MM", s: "SS" }}
onFinish={() => console.log('finished')}
//on Finish call
size={30}
/>
</View>
)
}
如前所述,当var d变为10时,我希望调用一个函数,直到安装该屏幕后即该应用程序被打开一次,才能调用该函数。
答案 0 :(得分:1)
我建议React Native Background Task,尽管它不能在特定时间可靠地执行任务(即:14:30可能在14:50执行),但它在git hub页面中的解释为
任务执行的确切时间是不可预测的,因为Anrdoid和iOS都使用黑盒算法,这取决于设备睡眠状态等因素。该库仅应用于具有增量功能的任务,并且可能具有不精确的时间安排,例如数据的定期后台同步。您应该为根本不执行后台任务的情况做好准备。