我正在尝试制作一个应用程序,它允许用户每天只访问一些信息一次,否则就会向用户展示他需要等待多长时间才能再次看到这些信息。
下面是我的代码:
long aux_time = prefs.getLong("AUX",System.currentTimeMillis());
Log.v(TAG, "aux=" + aux_time);
Log.v(TAG, "time" + System.currentTimeMillis());
if(System.currentTimeMillis() > aux_time + (10000 * 60 * 60 * 24))
{
finish();
Intent intent = new Intent(Castle.this, Hug.class);
startActivity(intent);
}
if (System.currentTimeMillis() >= aux_time + (10000 * 60 * 60 * 24))
{
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("AUX", System.currentTimeMillis());
editor.commit();
finish();
Intent intent = new Intent(Castle.this, Hug_Accepted.class);
startActivity(intent);
}
我测试了代码。我相信,它是在24小时后打开的,但是当我第一次打开活动时,它不会打开,因为当我在第二个if中比较时,两者之间有0.00000000001毫秒的差异。有什么想法吗?
发布于 2012-03-14 22:30:28
除了Jave's answer之外
if (System.currentTimeMillis() > aux_time + (1000 * 60 * 60 * 24))
。这里检查当前时间是否大于aux_time至少24小时。发布于 2012-03-14 22:12:30
在你的应用中,你所要做的就是有一个数据库或者本地文件来记录日常使用情况。因此,例如,如果您有一个数据库,其中包含列"id“、"lastViewed”( mills中的时间或字符串形式的日期)。
现在,每次运行主要活动时,在onCreate中检查数据库中的lastViewed是否是昨天或更早的,如果不是,则向用户显示适当的消息,否则让用户进入并在数据库中标记日期和时间。
发布于 2012-03-14 22:22:32
您的代码非常奇怪,首先,您在一些if-block中调用finish()
,但不调用return;
,这意味着您将继续计算下一个if - block (在您检查是否为millis == aux_time
的代码中,您设置了k=1
,这意味着下一个块k==1
将始终运行)。
其次,您正在比较的时间单位是毫秒,除非调用两次相同的毫秒,否则System.currentTimeMillis()==aux_time
永远不会是真的,但也许我误解了您的代码?
https://stackoverflow.com/questions/9703506
复制相似问题