1

In my app user pick a date and time from a date and time picker (from the past dates) then I want to start a count up timer from that date and I need to run it in a service so that if my app killed, timer wouldn't stop. I've tried Chronometer and some similar solution on stackOverFlow but didnt get any correct solution.

Please check below picture, that It is so similar to what I need:

https://ibb.co/rFz24kg

Parisa Baastani
  • 1,713
  • 14
  • 31
  • 1
    You don't need to run some kind of service or some fancy stuff for this to work. Simply just store the selected date in SharedPreferences, then when you go inside the view which has the counter you can start your counter with selected date as a reference – Carnal Apr 23 '19 at 11:39
  • Do you want to show this timer after user opens the app or do you want something like a home screen widget? – Shrey Garg Apr 23 '19 at 11:40
  • @ShreyGarg I just want to show the timer whenever user open the app. – Parisa Baastani Apr 23 '19 at 11:42
  • then you do not really need a Service for doing this, as @Carnal suggested, you can save the datetime in shared preferences, and when the app is opened - calculate time diff and start a count up timer – Shrey Garg Apr 23 '19 at 11:44
  • My main another problem is how to make a count up timer from a specific date that user pick. – Parisa Baastani Apr 23 '19 at 11:46
  • @ParisaBaastani, please check my answer – Shrey Garg Apr 23 '19 at 11:56

1 Answers1

1

For getting the difference in the dates (here, date2 can be the user-picked date and date1 can be current datetime (which you can get by calling : new Date())):

public static String getDifferenceBetweenDates(Date date1, Date date2) {
    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long difference = date2.getTime() - date1.getTime();

    long elapsedDays = difference / daysInMilli;
    difference = difference % daysInMilli;

    long elapsedHours = difference / hoursInMilli;
    difference = difference % hoursInMilli;

    long elapsedMinutes = difference / minutesInMilli;
    difference = difference % minutesInMilli;

    long elapsedSeconds = difference / secondsInMilli;

    return String.format("%s days %s hours %s minutes %s seconds", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}

Now once you get the difference, you can use this as a Count Up Timer and define onTick() to update your view every mCountUpInterval time interval (defined in the CountUpTimer class)

Shrey Garg
  • 1,317
  • 1
  • 7
  • 17