Question

i have made a chronometer in my app. but when i turn of the screen in my phone after a while i look to see how much time passed and the chronometer is at zero again. how do i fix it so it doesent reset by itself?

    if(v.getId() == R.id.start){
        int stopsecs = 0;

          String chronotime = time.getText().toString();
          String currenttime[] = chronotime.split(":");
          if (currenttime.length == 2) {
            stopsecs = Integer.parseInt(currenttime[0]) * 60 * 1000
               + Integer.parseInt(currenttime[1]) * 1000;
          } else if (currenttime.length == 3) {
            stopsecs = Integer.parseInt(currenttime[0]) * 60 * 60 * 1000 
                + Integer.parseInt(currenttime[1]) * 60 * 1000
                + Integer.parseInt(currenttime[2]) * 1000;
          }

          time.setBase(SystemClock.elapsedRealtime() - stopsecs);
          time.start();

    }
    else if(v.getId() == R.id.stop){
        time.stop();
        String updatedtime[] = time.getText().toString().split(":");
        StringBuilder b = new StringBuilder();
        if(updatedtime.length == 2){
            b.append("0");
            b.append(".");
            b.append(updatedtime[0]);
        }
        else if(updatedtime.length == 3){
            b.append(updatedtime[0]);
            b.append(".");
            b.append(updatedtime[1]);
        }
        horasch.setText(b.toString());

        time.setBase(SystemClock.elapsedRealtime());

    }
    else if(v.getId() == R.id.pause){
        time.stop();

    }
Was it helpful?

Solution

You don't indicate what time.start() and time.stop() do, but I assume it's some kind of timer or thread. When you turn off the screen, or use another app, your Activity will be paused and subject to being killed by the runtime. So when you return to it, onCreate() will run again.

Override the method onSaveInstanceState() to save the state of your chronometer at the end of the Activity's active lifetime (for example store whether started/stopped and the basetime in SharedPreferences). So if your app is killed, you then have the information required to restore its state when it restarts.

Override the method onRestoreInstanceState() to restore the state of your chronometer from the data you stored in SharedPreferences. Note that this method is only called if the Activity was killed by the system since it was last visible and it runs after onCreate().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top