是否已有一个秒表类,Android和为什么我的执行工作? [英] Is there already a StopWatch class for android and why doesn't my implementation work?
问题描述
最近我看到 http://developer.android.com/reference/android /os/CountDownTimer.html 并想知道是否有相应的类秒表,因为我想告诉我的应用程序的用户多长时间,他已经试图解决这一难题。我的意思是不那么复杂编程你自己这样一个秒表。我想是这样
Lately I saw http://developer.android.com/reference/android/os/CountDownTimer.html and wondered if there is an respective class for stop watches since I want to tell the user of my App how long he's already trying to solve the puzzle. I mean it isn't that complicated to program such a stop watch on your own. I tried something like
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
long seconds = (System.currentTimeMillis() - t) / 1000;
statusBar.setText(String.format("%02d:%02d", seconds / 60, seconds % 60));
}
}
};
statusBar.post(runnable);
不过,奇怪的是我的活动的布局是不是夸大了,因为我有这样的 statusBar.post(可运行);
中的活性的研究的的onCreate
方法,即启动该应用程序后,我只看到,而不是正常的GUI白屏。
But bizarrely the layout of my activity isn't inflated anymore since I have this statusBar.post(runnable);
in the end of the acitivity's onCreate
method meaning that after starting the app I only see a white screen instead of the normal gui.
推荐答案
您应该使用一个天文台。
You should use a Chronometer.
但无论如何,你的code能如果从UI线程删除休眠工作。
But anyway, your code can work if you remove the sleep from UI thread.
private final Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (mStarted) {
long seconds = (System.currentTimeMillis() - t) / 1000;
statusBar.setText(String.format("%02d:%02d", seconds / 60, seconds % 60));
handler.postDelayed(runnable, 1000L);
}
}
};
private Hanlder mHandler;
private boolean mStarted;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
}
@Override
protected void onStart() {
super.onStart();
mStarted = true;
mHandler.postDealyed(runnable, 1000L);
}
@Override
protected void onStop() {
super.onStop();
mStarted = false;
mHandler.removeCallbacks(mRunnable);
}
这篇关于是否已有一个秒表类,Android和为什么我的执行工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!