我们开启一个线程,线程每隔一秒发送一次消息,我们在消息中更新TextView上显示的时间就ok了。
首先我们在布局文件中放一个TextView用来显示时间,如下所示:
之后我们写一个线程,线程里面无限循环,每隔一秒发送一个消息,其中由Handler来处理显示的结果:
private Handler mHandler = new Handler() {
@Override
public void handleMessage (Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case msgKey1:
long sysTime = System.currentTimeMillis();
CharSequence sysTimeStr = DateFormat.format("hh:mm:ss", sysTime);
mTime.setText(sysTimeStr);
break;
default:
break;
}
}
};
之后我们可以在Activity的onCreate方法中开启这个线程,这时我们可以看到一个数字时钟了:
整个Activity的代码:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.widget.TextView;
public class TestActivity extends Activity {
private static final int msgKey1 = 1;
private TextView mTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
mTime = (TextView) findViewById(R.id.mytime);
new TimeThread().start();
}
public class TimeThread extends Thread {
@Override
public void run () {
do {
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = msgKey1;
mHandler.sendMessage(msg);
}
catch (InterruptedException e) {
e.printStackTrace();
}
} while(true);
}
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage (Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case msgKey1:
long sysTime = System.currentTimeMillis();
CharSequence sysTimeStr = DateFormat.format("hh:mm:ss", sysTime);
mTime.setText(sysTimeStr);
break;
default:
break;
}
}
};
}