gpt4 book ai didi

java - 在 Activity 中设置计时器的最有效方法

转载 作者:行者123 更新时间:2023-12-01 14:58:55 25 4
gpt4 key购买 nike

我想要一个计时器来计算用户完成任务所需的时间。根据 stackoverflow 上的其他问题,我设计了以下方法(参见下面的代码)。我的问题 -> 有更有效的方法吗?好像有点麻烦。

    private Timer myTimer;
private SharedPreferences prefs;
private String prefName = "MyPref";
private static final String TIMER_KEY = "timer";
private static final String FINAL_TIMER_KEY = "final timer";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crossword1);

//Start the timer ticking
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}

}, 0, 1000);
}

private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}

private Runnable Timer_Tick = new Runnable() {
public void run() {

//here i plan on using a shared preference to keep track of the time
//so each "Timer_Tick" would get the latest "TIMER_KEY", add a second to it
//and then re-store it in the shared preferences

}
};

最佳答案

通过使用以下代码,您可以将时间打印为 TextView 和背景。

private Long startTime;
private Handler handler = new Handler();
startTime = System.currentTimeMillis();

handler.removeCallbacks(updateTimer);
handler.postDelayed(updateTimer, 1000);

private Runnable updateTimer = new Runnable() {
public void run() {
final TextView time = (TextView) findViewById(R.id.timer);
Long spentTime = System.currentTimeMillis() - startTime;
//計算目前已過分鐘數
Long minius = (spentTime/1000)/60;
//計算目前已過秒數
Long seconds = (spentTime/1000) % 60;
time.setText(minius+":"+seconds);
handler.postDelayed(this, 1000);
}
};

关于java - 在 Activity 中设置计时器的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13972647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com