0

I am beginner in Android. In my application i want to check if 24 hours passed or not.

I tried code from this article:How to count that 24 Hours passed or not , but when i changed Data and Time settings in my phone, toast still doesn't work. Thanks for help

   // Save current time
    long savedMillis = System.currentTimeMillis();

   // Check time elapsed
    if (System.currentTimeMillis() >= savedMillis + 24 * 60 * 60 * 1000) {
        Toast.makeText(this,"ABC",Toast.LENGTH_SHORT).show();
    }
D.MARKO
  • 3
  • 2

1 Answers1

0

Here you go, try this

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
long nextTime = sp.getLong("nextTime", 0);
// Check time elapsed
if (System.currentTimeMillis() >= nextTime) {
    Toast.makeText(this,"ABC",Toast.LENGTH_SHORT).show();
    SharedPreferences.Editor editor = sp.edit();
    editor.putLong("nextTime", (System.currentTimeMillis() + (24 * 60 * 60 * 1000)));
    editor.commit();
}
Deˣ
  • 4,191
  • 15
  • 24
  • Thank you @Derek, but now toast is always displayed when the application is starting (no matter if the date in the settings will be changed) – D.MARKO Jun 20 '19 at 15:44
  • sorry, it was my mistake. I have updated the answer. Check now. – Deˣ Jun 20 '19 at 16:00
  • Thank you very much @Derek, now it works perfectly:), Could you tell me why the "old" version from my post doesn't worked? – D.MARKO Jun 20 '19 at 16:05
  • Your `savedMillis` is an instance value which gets cleared as soon as the method call ends. You need to save the value till the next method call which can be achieved either by saving to sharedpreference or database. – Deˣ Jun 20 '19 at 16:22
  • Ok, Thank you one more time:) – D.MARKO Jun 20 '19 at 16:24