我们开启一个线程,线程每隔一秒发送一次消息,我们在消息中更新TextView上显示的时间就ok了。
首先我们在布局文件中放一个TextView用来显示时间,如下所示:
复制代码 代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white">
<TextView
android:id="@+id/mytime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="@android:color/black"
android:textSize="36sp"/>
</LinearLayout>
之后我们写一个线程,线程里面无限循环,每隔一秒发送一个消息,其中由Handler来处理显示的结果:
复制代码 代码如下:
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;
}
}
};
之后我们可以在Activity的onCreate方法中开启这个线程,这时我们可以看到一个数字时钟了:
复制代码 代码如下:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
mTime = (TextView) findViewById(R.id.mytime);
new TimeThread().start();
}
整个Activity的代码:
复制代码 代码如下:
package com.fermax.test;
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;
}
}
};
}