0

我在我的应用程序中制作了一个计时器。但是,当我在一段时间后转动手机屏幕时,我会查看经过了多少时间,而计时器又归零了。我该如何修复它,使其不会自行重置?

    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();

    }
4

1 回答 1

0

您没有说明 time.start() 和 time.stop() 做什么,但我认为它是某种计时器或线程。当您关闭屏幕或使用其他应用程序时,您的 Activity 将被暂停并被运行时杀死。因此,当您返回它时, onCreate() 将再次运行。

重写 onSaveInstanceState() 方法以在 Activity 的活动生命周期结束时保存计时器的状态(例如,将是否启动/停止以及在 SharedPreferences 中的基准时间存储)。因此,如果您的应用程序被终止,您将获得在重新启动时恢复其状态所需的信息。

重写 onRestoreInstanceState() 方法以从存储在 SharedPreferences 中的数据中恢复计时器的状态。请注意,仅当 Activity 自上次可见以来被系统杀死并且在 onCreate() 之后运行时才调用此方法。

于 2014-01-17T10:46:20.343 回答