Android / Java - 设置和比较日期与偏移量

时间:2011-02-06 04:06:55

标签: android time compare sharedpreferences

我正在开发一个应用程序,该应用程序从每天晚上9点(AEDT时间)更新的网页获取数据。 获取数据后,使用共享首选项存储数据。

如果我们知道自上次获取页面以来页面没有更新,那么获取数据是没有意义的,我正在尝试实现以下内容:

1)获取数据时,设置当前时间的时间戳优先值
2)当应用程序获取数据时,检查当前时间是否“在最后一次获取日期的下一个9pm之后”
3)如果是,则获取数据,否则显示消息,表明不需要更新。

我不确定如何将当前日期存储为可以存储在共享首选项中的原语...也许System.currentTimeMillis()(返回一个长)?这是以UTC格式返回的......需要确保所有设置和检查都使用相同的时区...

如何检查当前时间是否超过“下一个晚上9点”的更新阈值?

(作为一个故障保护,用户有一个强制更新的菜单按钮 - 如果应用确定不需要更新,将会提及。)

编辑:我想我已经解决了,但仍会感谢任何反馈或建议 - 见下文。

2 个答案:

答案 0 :(得分:0)

我相信在这种情况下,您需要在您的应用中实施服务。只要确保你没有在你的服务中运行不必要的代码,否则用户的电池就会受到影响!请参阅此页http://developer.android.com/reference/android/app/Service.html

答案 1 :(得分:0)

我想我已经找到了解决方案。

获取数据时,完成以下操作......

editPrefs.putLong("fetchTime", System.currentTimeMillis());


当应用程序启动并且通常请求数据时,它现在会执行..
注意:该页面每天更新“AEDT晚上9点” - (澳大利亚东部夏令时),我认为当夏令时结束时,它将更改为AEST(澳大利亚东部标准时间)。“澳大利亚/ ACT“是这些区域的时区”

//create calendar date for update threshold based on last fetch time preference
Calendar updateThresh = new GregorianCalendar(TimeZone.getTimeZone("Australia/ACT"));
updateThresh.setTimeInMillis(prefs.getLong("fetchTime", 0));

//increment day if last fetch was >= 9pm of that day
if (updateThresh.get(Calendar.HOUR_OF_DAY) >= 21)
    updateThresh.add(Calendar.DAY_OF_MONTH, 1);

//set time to 9:00:00pm
updateThresh.set(Calendar.HOUR_OF_DAY , 21);
updateThresh.set(Calendar.MINUTE , 0);
updateThresh.set(Calendar.SECOND , 0);

//check if current date is before or after
if (updateThresh.before(new GregorianCalendar(TimeZone.getTimeZone("Australia/ACT"))))
{
    //update needed (fetch data)
}
else
{
    //update not needed (show message)
}

这似乎工作正常。我使用DateFormat设置到澳大利亚/ ACT进行了测试,它似乎有效......例如创建另一个设置为获取时间的日历对象并使用:

DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("Australia/ACT"));

testTextField.setText("Last fetch in East AU time: " + df.format(fetchTime.getTimeInMillis()) + 
    "\nUpdate threshold in East AU time: " + df.format(updateThresh.getTimeInMillis()) );

即使我在手机上使用时区设置,这也能让我始终正确输出...我相当确定这个解决方案有效,所以我会将其标记为正确/接受 - 但如果有人注意到错误或有更好的建议,随时贡献! :)