Android Chronometer - 节省时间

时间:2015-08-18 17:49:29

标签: android screen-rotation chronometer

我在我的Android应用程序中使用计时器。我可以启动它,停止它并在再次按下启动按钮后继续计数:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_projektbeschreibung, container, false);



    if (savedInstanceState != null){
        stoppedmillis = savedInstanceState.getLong(STATE_TIME);
        hh = savedInstanceState.getString(STATE_HH);
        mm = savedInstanceState.getString(STATE_MM);
        ss = savedInstanceState.getString(STATE_SS);

    }



    mChronometer = (Chronometer) rootView.findViewById(R.id.chronometer2);
    mChronometer.setText(hh + ":" + mm + ":" + ss);
    mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer cArg) {
            long time = SystemClock.elapsedRealtime() - cArg.getBase() ;
            int h = (int) (time / 3600000);
            int m = (int) (time - h * 3600000) / 60000;
            int s = (int) (time - h * 3600000 - m * 60000) / 1000;
            hh = h < 10 ? "0" + h : h + "";
            mm = m < 10 ? "0" + m : m + "";
            ss = s < 10 ? "0" + s : s + "";
            cArg.setText(hh + ":" + mm + ":" + ss);

        }
    });


    ((Button) rootView.findViewById(R.id.startbutton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //if first start
            if(stoppedmillis == 0) {
                mChronometer.setBase(SystemClock.elapsedRealtime());


            } else {//Point A
                long pausetime = (SystemClock.elapsedRealtime() - stoppedmillis);
                mChronometer.setBase(mChronometer.getBase() + pausetime);
            }
            mChronometer.start();

        }
    });

    ((Button) rootView.findViewById(R.id.stopbutton)).setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
        mChronometer.stop();
        stoppedmillis = SystemClock.elapsedRealtime();
        }
    });

屏幕旋转后(活动重新开始),计时器再次从00:00:00开始计数。我的第一次尝试是使用stoppedmillis方法保存onSaveInstanceState,如下所示:

 public void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putLong(STATE_TIME, stoppedmillis);
    savedInstanceState.putString(STATE_HH, hh);
    savedInstanceState.putString(STATE_MM, mm);
    savedInstanceState.putString(STATE_SS,ss);

    super.onSaveInstanceState(savedInstanceState);
}

现在,我可以在重启后获得stoppedmillis的值,但我不知道如何在stoppedmillis的帮助下为计时器设置基数。在代码中的A点,您可以看到它如何通过按钮停止计时器,但这部分代码在屏幕旋转后不起作用。

4 个答案:

答案 0 :(得分:0)

我知道这是旧的。虽然,我已经使用计时器创建了一个简单的应用程序,并完成了以下操作,它一直在屏幕旋转计数。这是Andrew的原始答案。以下是我的概述:

Chronometer mChronometer; // this is a global variable

@Override
protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     mChronometer = (Chronometer)findViewById(R.id.chronometer);


    if(savedInstanceState != null){

       mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
       mChronometer.start();
          }

    }

现在设置onSaveInstanceState:

  @Override
  public void onSaveInstanceState (Bundle savedInstanceState){
     super.onSaveInstanceState(savedInstanceState);

     savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
   }

答案 1 :(得分:0)

快速解决方案,使用此类: https://github.com/ahmedrizwan/ChronometerPersist/blob/master/chronometerpersist/src/main/java/library/minimize/com/chronometerpersist/ChronometerPersist.java

ChronometerPersist chronometerPersist = ChronometerPersist.getInstance(chronometer, sharedPreferences);

//Starting the chronometer
startChronometer();
//Stoping the chronometer
stopChronometer();
//Pausing the chronometer
pauseChronometer();

我已经失去了很多时间尝试使用安卓计时器小部件恢复当前时间。

答案 2 :(得分:0)

这就是我解决保存计时器状态的方法。

 private static final int TIME_MULTIPLIER = 60;

第1步 :将时间转换为秒数:

注意:如果您不喜欢我将时间转换为秒的方法,那么您可以按照自己的方式行事。

 private static int convertTimeToSeconds(Long... time) {
    int seconds = 0;
    if (time.length == 2) {
        seconds += time[0] * TIME_MULTIPLIER + time[1];
    } else if (time.length == 3) {
        seconds += (time[0] * TIME_MULTIPLIER) + (time[1] * TIME_MULTIPLIER) + (time[2]);
    }
    return seconds;
}

第2步: 天文台的设定和开始时间

注意:我将数据保存在自定义对象中,使用任何数据库/ SharedPreference /您的愿望保留该对象。

 public static void setAndStartTime(final Chronometer chronometer) {
    long second = 0;

   // i have multiple time saved into map. You could save just 1 time and reuse that time.
    for (DailyData data : DailyData.DailyDataHolder.getDailyDataMap().values()) {
        second += data.getDailyTimeSpent();
    }
    chronometer.setBase(SystemClock.elapsedRealtime() - (second * 1000));
    chronometer.start();
}

第3步: 节省时间:

public static void saveTime(String timeText) {
    String[] timeParts = timeText.split("[:]");
    long savedTime = 0;
    if (timeParts.length == 2) {
        savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]));
    } else if (timeParts.length == 3) {
        savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]), Long.parseLong(timeParts[2]));
    }
    DailyData.DailyDataHolder.getDailyData().setDailyTimeSpent(savedTime);
}

调用已保存的方法:

      ChronoHelper.saveTime(chronometer.getText().toString());

完整课程:

public class ChronoHelper {

private static final int TIME_MULTIPLIER = 60;

public static void setAndStartTime(final Chronometer chronometer) {
    long second = 0;
    for (DailyData data : DailyData.DailyDataHolder.getDailyDataMap().values()) {
        second += data.getDailyTimeSpent();
    }
    chronometer.setBase(SystemClock.elapsedRealtime() - (second * 1000));
    chronometer.start();
}

public static void saveTime(String timeText) {
    String[] timeParts = timeText.split("[:]");
    long savedTime = 0;
    if (timeParts.length == 2) {
        savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]));
    } else if (timeParts.length == 3) {
        savedTime = convertTimeToSeconds(Long.parseLong(timeParts[0]), Long.parseLong(timeParts[1]), Long.parseLong(timeParts[2]));
    }
    DailyData.DailyDataHolder.getDailyData().setDailyTimeSpent(savedTime);
}

private static int convertTimeToSeconds(Long... time) {
    int seconds = 0;
    if (time.length == 2) {
        seconds += time[0] * TIME_MULTIPLIER + time[1];
    } else if (time.length == 3) {
        seconds += (time[0] * TIME_MULTIPLIER) + (time[1] * TIME_MULTIPLIER) + (time[2]);
    }
    return seconds;
}

public static String secondsToTimeText(DailyData dailyData) {
    long savedSeconds = dailyData.getDailyTimeSpent();
    long minutes = savedSeconds / TIME_MULTIPLIER;
    long seconds = savedSeconds % TIME_MULTIPLIER;
    long hours = minutes / TIME_MULTIPLIER;
    return hours + ":" + minutes + ":" + seconds;
   }
}

答案 3 :(得分:-1)

将计时器的基准时间保存在onSaveInstanceState并将其重新设置为onRestoreInstanceState,如下所示:

public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
    super.onSaveInstanceState(savedInstanceState);
}

public void onRestoreInstanceState(Bundle savedInstanceState){
    if((savedInstanceState !=null) && savedInstanceState.containsKey("ChronoTime"))
        mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
    super.onRestoreInstanceState(savedInstanceState);
}