2012-03-14 87 views
0

我正在试图制作一个应用程序,允许用户每天只访问一次信息,以向用户显示他需要等待多长时间才能再次看到该信息。
这里是我的代码:每日申请

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小时后会打开,但是当我第一次打开该活动时它不会打开,因为当我在第二个项目中比较它们时,这两者之间存在0.00000000001毫秒的差异。有任何想法吗?

回答

1

除了Jave's answer

  1. 不检查与当前时间的平等,而不是检查if (System.currentTimeMillis() > aux_time + (1000 * 60 * 60 * 24))。 在这里检查当前时间是否大于aux_time至少24小时 。
  2. 'k'在这里的作用是什么?它的价值从未被使用过。
+1

或者他可以在这种情况下使用'日历'或'时间'对象来避免特殊情况下每天的时间多于/少于24小时(夏令时)的问题。 – Jave 2012-03-14 14:33:17

+0

我正在这样想。用户对该受限活动的访问权限存储在k中。当k == 1时,用户可以输入活动,如果它是0,则不输入。我正在尝试做这样的事情。 K将保持为0,直到当前时间=辅助时间(即使应用程序关闭),当相等为真时,在活动开始之前,k = 1也是真实的。 – AnTz 2012-03-14 19:41:36

+0

试过这个。我相信这个代码对我来说是对的,但我的应用程序总是允许用户输入活动,不知道为什么。 – AnTz 2012-03-14 19:47:59

0

好吧,你必须在你的应用程序中做的事情是有某种数据库或本地文件来跟踪日常使用情况。所以例如,如果你有一个数据库的列“id”,“lastViewed”(时间在工厂或日期字符串)。

现在每次你运行你的主要活动,在onCreate检查数据库,如果lastViewed是昨天或更早,如果不是,则显示用户适当的消息,否则让用户在数据库日期和时间标记。

+0

好的,好的。我有想法,但我无法设法编写有效的代码。 – AnTz 2012-03-14 14:23:00

0

你的代码是很奇怪的,首先,你调用一些,如果块的finish(),但不return;,这意味着你会继续,你是否millis == aux_time评估未来如果块(在一个你设置为k=1这意味着下一个区块k==1将始终运行)。

其次,你比较毫秒System.currentTimeMillis()==aux_time的时间,除非调用了两次相同的毫秒将永远是真实的,但也许我误解你的代码?

+0

感谢您的回复。完成后()我有一个意图,改变我的活动。至于比较的事情,是的,那是我的问题,我不知道如何解决它。我会尝试Dheeraj的回答,看看它是否有效。 – AnTz 2012-03-14 19:39:11

0

这是我的工作版本的代码。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 

    long aux_time = prefs.getLong("AUX",0); 
    Log.v(TAG, "aux=" + aux_time); 
    Log.v(TAG, "time" + System.currentTimeMillis()); 

    if(aux_time==0) 
    { 
     SharedPreferences.Editor editor = prefs.edit(); 
     editor.putLong("AUX", System.currentTimeMillis()); 
     Log.v(TAG, "aux2" + aux_time); 
     editor.commit(); 

    //Open restricted activity 
    } 

    if(System.currentTimeMillis() < aux_time + (10000 * 60 * 60 * 24)) 
    { 


     //Open the "Not Allowed" activity 
    }   

    if(System.currentTimeMillis() > aux_time + (10000 * 60 * 60 * 24)) 
    { 
     SharedPreferences.Editor editor = prefs.edit(); 
     editor.putLong("AUX", System.currentTimeMillis()); 
     Log.v(TAG, "aux2" + aux_time); 
     editor.commit(); 


     //Open the restricted one 
    }