Search code examples
javaandroidgithubtimeropen-source

Countdown timer bug after midnight (Related to Timezone and Clock )


I've got a couple of users in my app reporting a weird behavior of a time reset/bug, i was baffled by it and after testing and collecting logs - i figured that my timer, if started before midnight, resets to 20+ hours instantly, i've can't figure out why or how to prevent this.

The project is open source and anyone is welcome to help me with this, here are the links:

GitHub

Info about the app/project:

  • Select apps, select desired lock-down time, lock apps.

My Timer Class ( Full )

Time/Date related snippet

 public class Timer_Service extends Service {

public static final long NOTIFY_INTERVAL = 1000;
public static String str_receiver = "com.nephi.getoffyourphone.receiver";
public String str_testing;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
//Root Detector
RootBeer rootbeer;
//Con Manager
WifiManager wifiManager;
//DH Helper
DB_Helper db;
Intent intent;
Intent lockIntent;
Intent Shame;
//Shame Int Counter
private Handler mHandler = new Handler();
private Timer mTimer = null;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    //Lock Screen launch
    lockIntent = new Intent(this, locked.class);
    lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    calendar = Calendar.getInstance();
    simpleDateFormat = new SimpleDateFormat("H:M:ss");

    mTimer = new Timer();
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
    intent = new Intent(str_receiver);

    //Root Detector
    rootbeer = new RootBeer(this);
    //Wifi Manager
    wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

    //DB
    db = new DB_Helper(this);
}  

public String twoDatesBetweenTime() {


    try {
        date_current = simpleDateFormat.parse(strDate);
    } catch (Exception e) {

    }

    try {
        // Gets the first timestamp when the lockdown started
        date_diff = simpleDateFormat.parse(db.get_Data(1));
    } catch (Exception e) {

    }

    try {


        long diff = date_current.getTime() - date_diff.getTime();
        int int_hours = Integer.valueOf(db.get_Hours(1));
        long int_timer;
        if (int_hours > 10) {
            int_timer = TimeUnit.MINUTES.toMillis(int_hours);
        } else {
            int_timer = TimeUnit.HOURS.toMillis(int_hours);
        }
        long long_hours = int_timer - diff;
        long diffSeconds2 = long_hours / 1000 % 60;
        long diffMinutes2 = long_hours / (60 * 1000) % 60;
        long diffHours2 = long_hours / (60 * 60 * 1000) % 24;


        if (long_hours >= 0) {
            str_testing = String.format("%d:%d:%02d", diffHours2, diffMinutes2, diffSeconds2);
            Log.e("TIME", str_testing);

        } else {
            stopService(new Intent(getApplicationContext(), Timer_Service.class));

            mTimer.cancel();
        }

Any suggestions ?


EDIT:

  • Timer works fine, if someone sets the lockdown for example, 30 minutes, it will countdown 30 minutes and unlock when it's done.

Let's say someone started the lockdown at 21:30:00, timer will work just fine and end at 10:00:00.

However, if someone started the lockdown at 23:55:00 for 30 minutes, the "Time left to unlock" will jump to 21 hours, instead of 30 minutes. This only happens when a new day starts/timer starts before midnight.


Solution

  • The problem occurs because you have the time stored in "H:m:ss" format, but you are ignoring the date aspect. Using System.currentTimeMillis() gives you the milliseconds after Jan 1 1970. So this includes the date aspect. Taking the difference of the two values will give you the milliseconds expired, which you can check against any time interval for the elapsed time.


    Do this instead:

    When saving the time for the timer should start use the millisecond instead of H:mm:ss :

    long millisNow = System.currentTimeMillis();
    

    save millisNow to the database.

    And save the time that should elapse:

    int minutes = 30;
    long millisElapse = 30 * 60 * 1000;
    

    save this to the database (or which ever time interval you need)

    now get the difference

    long diff = timeNow - timeDatabase;
    
    if(diff > millisElapse){
        //end session
    }
    


    BTW: The format you posted "H:M:ss". The capital "M" stands for month(!) not minutes.
    Take a look at the documentation on the "Date and Time Patterns" SimpleDateFormat