首页  编辑  

安卓按指定时刻开始周期性运行任务

Tags: /Android/   Date Created:
安卓中,如何从指定时刻开始,周期性定时运行任务?
例如每天8:00:00运行某个任务,19:00运行某个任务?
或者每分钟运行一次某个任务?
class HMS {
int hour;
int minute;
int second;
}

Timer tmrGetData;
Timer tmrPowerOn;
Timer tmrPowerOff;
Timer tmrSimSwith;

private void setTimer()
{
// 采样每隔指定时间周期性运行即可运行
if (tmrGetData != null) tmrGetData.cancel();
tmrGetData = new Timer();
tmrGetData.schedule(new TimerTask() {
@Override
public void run() {
GetData(); // GetData为MainActivity的方法!
}
},5000,1000 * SampleRate);
// 指定时间的任务,必须在指定的时刻才运行,同时是每天这个时刻都要重复运行的

Date date = new java.util.Date();

date.setHours(PowerOn.hour);
date.setMinutes(PowerOn.minute);
date.setSeconds(PowerOn.second);
if (tmrPowerOn != null) tmrPowerOn.cancel();
tmrPowerOn = new Timer();
tmrPowerOn.schedule(new TimerTask() {
@Override
public void run() {
powerControl(true);
}
}, date, PERIOD_DAY);

date.setHours(PowerOff.hour);
date.setMinutes(PowerOff.minute);
date.setSeconds(PowerOff.second);
if (tmrPowerOff != null) tmrPowerOff.cancel();
tmrPowerOff = new Timer();
tmrPowerOff.schedule( new TimerTask() {
@Override
public void run() {
powerControl(false);
}
}, date, PERIOD_DAY);

date.setHours(SimSwitch.hour);
date.setMinutes(SimSwitch.minute);
date.setSeconds(SimSwitch.second);
if (tmrSimSwith != null) tmrSimSwith.cancel();
tmrSimSwith = new Timer();
tmrSimSwith.schedule(new TimerTask() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
@Override
public void run() {
SwitchSimCard(1);
}
}, date, PERIOD_DAY);
}