How to creating a an which counting work time

37 Views Asked by At

I am developing an app which count time of working when user click start button starts the work when click button end work, ends work. App should count time even if the app is killed or phone is down. I use the foreground service and here is a problem cous foreground service shows wrong value when I using thread.sleep(1000), timerTask works weird after long time and second problem is that foreground service is killed by os and everything count at the begining.

I try SharedPref, ExecutorService, Handler, Timer, Stopwatch class, wakelock and nothing works. I give up and not counting time like real stopwatch but i assign two values to System.currentTimeMillis() one for start and one for current time to and using thread.sleep(1000) and assigning this value to Shared pref. But what was I excepting was real stopwatch. I am trying to do with work manager but the same thing with restart the foreground service.

1

There are 1 best solutions below

0
Shovel_Knight On

I haven't tried this solution specifically on Android, but it works in Java 8.

When the user is clocking in:

LocalDateTime clockIn = LocalDateTime.now();
String clockInAsString = clockIn.toString();

Now you can save clockInAsString using SharedPreferences.

When the user later opens the app and clocks out, first read the string from SharedPreferences and then...

int SECONDS_PER_MINUTE = 60;
int MINUTES_PER_HOUR = 60;
int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
LocalDateTime clockIn = LocalDateTime.parse(clockInAsString);
LocalDateTime clockOut = LocalDateTime.now();
Duration workDuration = Duration.between(clockIn, clockOut);
long seconds = workDuration.getSeconds();
long workHours = seconds / SECONDS_PER_HOUR;
long workMinutes = (seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE;
long workSeconds = seconds % SECONDS_PER_MINUTE;

I would even consider using SQLite and saving all clock in and clock out events to a database. This way you would be able to keep clock in and clock out history, and also warn the user if they have forgotten to clock in or out (for example, if the last event is a clock out event, the user should not be able to create a new clock out event without clocking in first).