I have been trying to create a custom stopwatch that counts up in android. It needs to be fairly accurate down to 0.1s and with custom layout and images for the digits example: DIGITS.
It also needs to be able to run in the background after the app has been minimized or closed. To be more specific, to force the app to stay open while the timer is on (I don't know how to achieve this).
So far I have tried using Handlers, Runnables, scheduledExecutorService and the android Chronometer class.
Handlers had issues with performance, chewing up 45%> cpu usage (I think this was because of the UI continuously updating?). I have managed to have it working using the scheduledExecutorService with modest performance, but it still has issue with continuing in the background or during orientation changes.
I am trying to create something similar to the default clock stopwatch on the HTC one M7. It works in the background and during orientation changes without losing any time.
The timer will be in its own Fragment in an Activity using a ViewPager and sliding tab layout.
This is the runnable for the stopwatch
public Runnable run() {
return new Runnable() {
@Override
public void run() {
centiseconds++;
if (centiseconds > 9) {
centiseconds = 0;
seconds++;
}
if (seconds > 59) {
seconds = 0;
minutes++;
}
if (minutes > 59) {
minutes = 0;
hours++;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
updateCustomUI();
}
});
}
};
}
In the fragment i then initialize the scheduledExecutorService
ScheduledFuture scheduledFuture;
ScheduledExecutorService scheduledExecutorService;
To start timer
scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(run(), 0, 100, TimeUnit.MILLISECONDS);
and to Stop it
scheduledFuture.cancel(true);