1
我想创建一个应用程序与需要在屏幕上显示一个时钟的React本机(只有几分钟需要更新正确,而不是秒)。该应用程序可能在屏幕上(可见)多分钟。反应本机时钟 - 设置一个很长一段时间的计时器
有没有一种正确的方法来做到这一点,就像我尝试过的每种方式都提出了“设置长时间的定时器,即多分钟,是Android上的性能和正确性问题......” 。
我怎样才能做到与正确性和影响最小一个简单的时钟电池等
时钟工作正常,我只是得到了警告。我已经尝试了各种方法,包括定期setTimeout/Interval和this.setTimeout,也反应本地背景计时器。
我也只需要更新时钟,当这个屏幕回到视图中,所以我取消了componentDidUnmount上的定时器。时钟只需要在几分钟内更新,而不是几秒钟,并且不需要100%准确,即在分钟更新完好之前有小的延迟。
谢谢!
代码:
import React, {Component} from 'react';
import {View, Image, AppState} from 'react-native';
import {Text} from 'react-native';
import Styles from '../../styles/Styles';
import BackgroundTimer from 'react-native-background-timer';
/*
Digital Clock
*/
export default class UIDigitalClock extends Component {
// Render -----------------
render() {
var label = this.formatAMPM(this.state.time);
return (
<Text style={[Styles.h0,{fontSize:80,opacity:0.7}]}>{label}</Text>
);
}
formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes;
return strTime;
}
//--------------------------------
constructor(props) {
super(props);
this.state = {
time: new Date()
}
}
timer = null;
componentWillMount() {
AppState.addEventListener('change', this.handleAppStateChange);
console.log('Digital Clock - Mount - Start');
this.startTimer();
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
this.stopTimer();
}
startTimer() {
return;
if (this.timer>0) return; // Already started
this.timer = BackgroundTimer.setInterval(() => {
// this will be executed every 200 ms
// even when app is the the background
this.updateTime();
}, 1000);
}
stopTimer() {
console.log("Digital Clock - stop ");
if (this.timer>0) {
BackgroundTimer.clearInterval(this.timer);
this.timer = -1;
}
}
handleAppStateChange = (appState) => {
console.log("Digital Clock app state: "+appState);
if (appState=='background') {
console.log('Digital Clock - App in Background - Stop');
this.stopTimer();
} else if (appState=='active') {
console.log('Digital Clock - App is Active - Start');
this.startTimer();
}
}
updateTime() {
let time = this.state.time;
let newTime = new Date();
// TODO - check if the app is in the foreground
console.log('Digital Clock - Tic ');
// Only update the render when the time changes...
if (!time || (time.getMinutes() != newTime.getMinutes() || time.getHours() != newTime.getHours())) {
console.log('Digital Clock - Time changed (mins/hours) - updating...');
this.setState({time: newTime});
}
}
}