java 判断新的一天_java - 检测到新的一天时调用方法

我希望我的应用程序能够在启动时检测到新的一天。如果是新的一天,我希望它开始新的 Activity 并重复该循环。第二天。

我从获取一年中某天的日历实例开始。Calendar c = Calendar.getInstance();

int thisDay = c.get(Calendar.DAY_OF_YEAR);

long todayMillis = c.getTimeInMillis();

然后,我将其存储在共享的首选项中并获取另一个日期

SharedPreferences prefs = PreferenceManager

.getDefaultSharedPreferences(this);

long last = prefs.getLong("date", System.currentTimeMillis());

c.setTimeInMillis(last);

int lastDay = c.get(Calendar.DAY_OF_YEAR);

我在每天创建支票并循环运行时遇到麻烦。

if (lastDay != thisDay) {

scheduleAlarm();

SharedPreferences.Editor edit = prefs.edit();

edit.putLong("date", todayMillis);

edit.commit();

}

我的解决方案如下。

Calendar c = Calendar.getInstance();

int thisDay = c.get(Calendar.DAY_OF_YEAR);

long todayMillis = c.getTimeInMillis();

SharedPreferences prefs = PreferenceManager

.getDefaultSharedPreferences(this);

long last = prefs.getLong("date", System.currentTimeMillis());

c.setTimeInMillis(last);

int lastDay = c.get(Calendar.DAY_OF_YEAR);

// Toast.makeText(getApplicationContext(),

// "lastday " + lastDay + "thisDay " + thisDay, Toast.LENGTH_LONG)

// .show();

if (lastDay == thisDay) {

scheduleAlarm();

SharedPreferences.Editor edit = prefs.edit();

edit.putLong("date", todayMillis + 86400000);

edit.commit();

}

最佳答案

除了重新计划之外,还可以指定period值(86400000 =每天)以重复通知。

该任务会将日期与存储的值进行比较,例如使用System.currentTimeMillis()持续存在一个时间戳记(SharedPreferences),以查明日期是否更改并将当前值写回到首选项中。

在启动时执行一次该任务。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值