Reputation: 33
I want do something like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
int i = (int) (new Date().getTime()/1000);
if( ) // next day
{
mymethod();
}
}
When in system date is a new day, then I want to call mymethod()
Upvotes: 2
Views: 2383
Reputation: 2653
With new day do you mean after midnight? So you want to detect if the date is different from last time?
@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();
}
}
Upvotes: 3
Reputation: 33
Great idea!
In my first activity I set something like this inside 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();
and use your code in another activity inside onCreate:
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();
}
}
I'm sorry for that but I'm still learning
Upvotes: 0