安卓毫秒
所以我试图编写一个以毫秒为单位显示时间的秒表应用程序,但由于某种原因它无法工作。基本上我只有一个切换按钮,按下后,开始打印从开始时间到当前时间的毫秒数...但在模拟器中,应用程序锁定了。怎么了?
public class testing extends Activity {
/** Called when the activity is first created. */
Button start,stop;
long init,now,time;
TextView display;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
display = (TextView) findViewById(R.id.chronometer1);
final ToggleButton passTog = (ToggleButton) findViewById(R.id.onoff);
passTog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
init=System.currentTimeMillis();
while(passTog.isChecked())
{
now=System.currentTimeMillis();
time=now-init;
display.setText("t: " + time);
}
}
});
}
}
So I'm trying to write a stopwatch app that displays time in milliseconds, but for some reason it won't work. Basically I have just a togglebutton that, after being pressed, starts printing the milliseconds from the start time to the current time... In the simulator though, the app locks up. What's wrong?
public class testing extends Activity {
/** Called when the activity is first created. */
Button start,stop;
long init,now,time;
TextView display;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
display = (TextView) findViewById(R.id.chronometer1);
final ToggleButton passTog = (ToggleButton) findViewById(R.id.onoff);
passTog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
init=System.currentTimeMillis();
while(passTog.isChecked())
{
now=System.currentTimeMillis();
time=now-init;
display.setText("t: " + time);
}
}
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您绝对不应该像在 OnClickListener 中那样运行繁忙循环。这就是应用程序锁定的原因。您需要让系统的其余部分有发言权。此外,每 30 毫秒左右更新一次显示是没有意义的,因为这大约是人眼可以跟踪的最快速度。此外,您可能希望在活动暂停时暂停计时器。这是一个可以完成所有这些操作的版本:
You definitely should not run a busy loop like you are doing inside the OnClickListener. That's why the app locks up. You need to let the rest of the system have its say. Also, it doesn't make sense to update the display more than once every 30 milliseconds or so, since that's about the fastest that the human eye can track. Also, you might want to suspend your timer when the activity is paused. Here's a version that does all that:
您将
setText()
方法放入onClick()
中,那么您会每秒单击该按钮吗?它甚至不是一个线程!
请尝试使用
CountDownTimer
类的onTick()
方法。You put the
setText()
method in youronClick()
, so will you click the button every second?Its not even a thread!
Try the
onTick()
method ofCountDownTimer
class instead.