<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<AnalogClock
android:id="@+id/myAnalogClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/info"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
package org.lxh.demo;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MyAnalogClockThreadDemo extends Activity {
private TextView info = null; // 文本显示组件
private static final int SET = 1; // 线程标记
private Handler handler = new Handler() { // 定义Handler对象
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SET: // 判断标志位
MyAnalogClockThreadDemo.this.info.setText("当前时间为:"
+ msg.obj.toString()); // 设置显示信息
break;
}
}
};
private class ClockThread implements Runnable { // 显示时间的线程类
@Override
public void run() { // 覆写run()方法
while (true) { // 持续更新
try {
Message msg = MyAnalogClockThreadDemo.this.handler
.obtainMessage(MyAnalogClockThreadDemo.SET,
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date())); // 实例化Message
MyAnalogClockThreadDemo.this.handler.sendMessage(msg); // 发送消息
Thread.sleep(1000); // 延迟1秒
} catch (Exception e) {
}
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main); // 调用布局文件
this.info = (TextView) super.findViewById(R.id.info); // 取得组件
new Thread(new ClockThread()).start(); // 启动线程
}
}