期待的效果: 从1开始计时,10秒之后,停止计时。
初始画面:
计时中画面:
计时到10秒之后结束的画面:
原理: 用handle 发送消息,处理消息的时候,判断是否已经达到10秒,没有达到10秒,接着再发送消息。
布局简单,不贴代码,主要看activity中的代码:
public class MainActivity extends Activity {
private Button btn_begin;
private TextView tv_time;
private int time = 0;
private int finalTime = 10;
//是否终止计时
private boolean terminateCount = false;
private HandlerThread mHandlerThread;
private Handler mTimeHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_begin = (Button) findViewById(R.id.btn_begin);
tv_time = (TextView) findViewById(R.id.tv_time);
mHandlerThread = new HandlerThread("count", 5);
mHandlerThread.start();// 开始计时
mTimeHandler = new Handler(mHandlerThread.getLooper());
}
public void doclick(View view){
mTimeHandler.post(oneSecondThread);
}
Thread oneSecondThread = new Thread(new Runnable() {
@Override
public void run() {
try {
if (time <=finalTime && !terminateCount) {
time++;
Thread.sleep(1000);
Message msg = new Message();
msg.arg1 = time;
uiHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
//接着传给ui更新
Handler uiHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (time <=finalTime && !terminateCount) {
tv_time.setText(msg.arg1 + " 秒");
mTimeHandler.post(oneSecondThread);
} else {
tv_time.setText("停止");
terminateCount = true;
}
}
};
}