运行 如果日期是第二天的方法

Run a method if Date is the next day

我想做这样的事情:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

 int i = (int) (new Date().getTime()/1000);

   if(      ) // next day
     {
         mymethod();
     }
}

当系统日期是新的一天时,我想调用mymethod()

建议使用Calendar class代替Date。你可以这样查看一天是否过去了:

  1. 在某些事件中,例如button click, app first start, 保存时间在sharedPreferences
  2. 检索该值并将其与当前时间进行比较 仅举例说明如何执行此操作:

    protected void onCreate(Bundle savedInstanceState){
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
    
        Calendar c = Calendar.getInstance(); 
        int currentTimeSeconds = c.get(Calendar.SECOND);
    
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int secondsPreviousDay = prefs.getInt("seconds", 0);
        if (secondsPreviousDay != 0){ //means there was an earlier set value from previously entering the activity
            //compare if more than 3600*24 = 86400 (1 day in seconds) had passed
            if (currentTimeSeconds - secondsPreviousDay > 86400){
                 mymethod();
            }
        }
        else {
            prefs.edit().putInt("seconds", currentTimeSeconds).apply();
        }
    }
    

在我的代码中,我假设您想查看从第一次开始 activity 到第二次开始是否过了一天。您可以根据自己的喜好进行调整,但我希望这个想法是可以理解的。

I know I could've compacted those 2 if's into one, but I just wanted it to be more clear what I was after.

好主意!

在我的第一个 activity 中,我在 onCreate 中设置了这样的东西:

 Calendar c = Calendar.getInstance();
    int currentTimeSeconds = c.get(Calendar.SECOND);
    SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor edittime = share.edit();
    edittime.putInt("timevalue",currentTimeSeconds);
    edittime.commit();

并在 onCreate 中的另一个 activity 中使用您的代码:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int secondsPreviousDay = prefs.getInt("seconds", 0);
    if (secondsPreviousDay != 0){ //means there was an earlier set value from previously entering the activity
        //compare if more than 3600*24 = 86400 (1 day in seconds) had passed
        if (currentTimeSeconds - secondsPreviousDay > 86400){
           // mymethod();
            mymethod();

        }
    }
    else {
        prefs.edit().putInt("seconds", currentTimeSeconds).apply();
    }
}

很抱歉,但我还在学习

新的一天是指午夜之后吗?所以你想检测日期是否与上次不同?

  @Override
  protected void onResume() {
     SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
     int lastTimeStarted = settings.getInt("last_time_started", -1);
     Calendar calendar = Calendar.getInstance();
     int today = calendar.get(Calendar.DAY_OF_YEAR);

    if (today != lastTimeStarted) {
      //startSomethingOnce();

      SharedPreferences.Editor editor = settings.edit();
      editor.putInt("last_time_started", today);
      editor.commit();
    }
  }