android – 使用postDelayed在特定时间运行任务
作者:互联网
我想在特定时间开始一项任务.为此我使用runnable和postDelayed方法如下:
private Runnable mLaunchTask = new Runnable() {
public void run() {
try {
MY TASK
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
在我的代码中,我使用如下的mLunchTask:
mHandler = new Handler();
mHandler.postDelayed(mLaunchTask, myDelay*1000);
和myDelay的计算方法如下:
s = DateFormat.format("hh:mm:ss aaa", d.getTime());
cTime = s.toString(); // current Time
ch = Integer.parseInt(cTime.substring(0,2)); // current hour
cm = Integer.parseInt(cTime.substring(3,5)); // current minute
cs = Integer.parseInt(cTime.substring(6,8)); // current second
if (cTime.substring(9,11).equalsIgnoreCase("pm") && (ch<12) ) ch = ch+12;
myDelay=(desiredHour-ch)*3600+(desiredMinute-cm)*60 - cs;
if (myDelay<0) myDelay = 0;
和desiredHour和desiredMinute由用户设置.期望是我的任务从期望的小时和期望的小时开始,0秒.
然而,“我的任务开始时有几秒延迟,看起来像是随机的.
基于上面的代码,是否有任何理由不能在确切的期望时间开始?
谢谢
解决方法:
首先,您的延迟计算是正确的,但“pm”检测不适用于其他语言.使用日历来获得延迟要好得多:
Calendar calendar = Calendar.getInstance();
long currentTimestamp = calendar.getTimeInMillis();
calendar.set(Calendar.HOUR_OF_DAY, desiredHour);
calendar.set(Calendar.MINUTE, desiredMinute);
calendar.set(Calendar.SECOND, 0);
long diffTimestamp = calendar.getTimeInMillis() - currentTimestamp;
long myDelay = (diffTimestamp < 0 ? 0 : diffTimestamp);
现在你有毫秒的延迟并且可以启动处理程序:
new Handler().postDelayed(mLaunchTask, myDelay);
在我的测试中,以下可运行的日志在所需的时间没有延迟.
private Runnable mLaunchTask = new Runnable() {
public void run() {
Calendar calendar = Calendar.getInstance();
Log.d("test", "started at "
+ calendar.get(Calendar.HOUR_OF_DAY) + " "
+ calendar.get(Calendar.MINUTE) + " "
+ calendar.get(Calendar.SECOND)
);
}
};
也许您的启动任务需要几秒钟才能加载?
AlarmManager可以替代吗?
标签:postdelayed,android,runnable 来源: https://codeday.me/bug/20190903/1795821.html