您将需要的是:
一个SharedPreference
描述最后日期的长值。
一个Calendar
。
当您的 Activity 开始时(在onCreate()
Method 中似乎是这样做的好地方),您可以获得一个新的Calendar
. 它将具有当前日期,您可以提取日期:
Calendar c = Calendar.getInstance();
int thisDay = c.get(Calendar.DAY_OF_YEAR); //You can chose something else to compare too, such as DATE..
long todayMillis = c.getTimeInMillis(); //We might need this a bit later.
然后,您从上次读取可能保存的值并将日历设置为该值,然后将其与今天进行比较:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
long last = prefs.getLong("date", 0); //If we don't have a saved value, use 0.
c.setTimeInMillis(last);
int lastDay = c.get(Calendar.DAY_OF_YEAR);
if( last==0 || lastDay != thisDay ){
//New day, update TextView and preference:
SharedPreferences.Editor edit = prefs.edit();
edit.putLong("date", todayMillis);
edit.commit();
}