Search code examples
javaandroidandroid-activitystopwatch

Stopwatch resets when activity restarts


I`m trying to create simple stopwatch for my statistics activity. What it needs to do is start when activity creates for the first time and then count and count until i reset it. The code I used:

    String trip_time;
    long millis;
    long start_time;
    Handler Handler;
    private boolean started = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Handler.postDelayed(Runnable, 10L);
        if (!started) {
            start_time = System.currentTimeMillis();
            started = true;
        }
     }

  private final Runnable Runnable = new Runnable() {
        @Override
        public void run() {
            millis = (System.currentTimeMillis() - start_time);
            long seconds = millis / 1000;
            trip_time = String.format(Locale.getDefault(), "%02d:%02d:%02d", seconds / 3600, seconds / 60, seconds % 60);
            Handler.postDelayed(Runnable, 10L);
        }
    };

But when I come to activity with intent, or activity restarts Stopwatch resets and starts counting from 0. After a few resets it continues counting from basic time. Can I somehow get rid of this problem? Probably via class or whatever.


Solution

  • Thank you, I solved my problem via making StopwatchService:

    public class StopwatchService extends Service {
    
        Handler Handler;
        long start_time;
        static String trip_time;
        static long millis;
    
        @Override
        public void onCreate() {
            super.onCreate();
            Handler = new Handler();
            Handler.postDelayed(Runnable, 10L);
            start_time = System.currentTimeMillis();
    
        }
        private final Runnable Runnable = new Runnable() {
            @Override
            public void run() {
                millis = (System.currentTimeMillis() - start_time);
                long seconds = millis / 1000;
                trip_time = String.format(Locale.getDefault(), "%02d:%02d:%02d", seconds / 3600, seconds / 60, seconds % 60);
                Handler.postDelayed(Runnable, 10L);
            }
        };
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        public static String getTrip_time(){return trip_time;}
    }
    

    In manifest:

     <service 
        android:name=".StopwatchService"
        android:enabled="true"/>
    

    And in activity:

     startService(new Intent(this, StopwatchService.class));
     String trip_time = StopwatchService.getTrip_time();