package com.bawei.layout;
import java.util.Calendar;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class TimeActivity extends Activity{
private static final int GUINOTIFIER =1;
//然后定义一些例子 里面需要的属性
public Calendar mCalendar;
// public int mMinutes;
// public int mHour; //小时
private int myear;//年
private int mmonth;//月
private int mday;//天
private int mminute;//分钟
private int mhour;//小时
private int msecond;//秒
private int mweek;//星期
private Handler mHandler;
private Thread mClockThread;
private TextView mtextview;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
mtextview = (TextView) findViewById(R.id.time_textview);
//接着我们通过Handler来接收Thread所传递的信息
result();
mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case TimeActivity.GUINOTIFIER://TestHandler是Activity的类名
//得到Handle的通知了 这个时候你可以做相应的操作,本例是使用TextView 来显示时间
mtextview .setText(myear + "年" + mmonth+"月"+ mday +"日"+mhour +":"+mminute+":"+msecond+"星期"+mweek);
break;
}
super.handleMessage(msg);
}
};
}
//接下来我们自定义一个Thread
class LooperThread extends Thread {
public void run() {
super.run();
try {
do {
//每间隔一秒取一次系统 时间
long time = System.currentTimeMillis();
final Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(time);
// 取得系统日期:
myear = mCalendar.get(Calendar.YEAR);
mmonth = mCalendar.get(Calendar.MONTH);
mday = mCalendar.get(Calendar.DAY_OF_MONTH);
// 取得系统时间:
mhour = mCalendar.get(Calendar.HOUR_OF_DAY);
mminute = mCalendar.get(Calendar.MINUTE);
msecond= mCalendar.get(Calendar.SECOND);
mweek = mCalendar.get(Calendar.DAY_OF_WEEK);
Thread.sleep(1000);
//取得系统时间后发送消息给Handler
Message m = new Message();
m.what = GUINOTIFIER;
mHandler.sendMessage(m);
} while (!LooperThread.interrupted());//当系统发出终端命令时停止循环
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//最后我们启动线程
public void result(){
mClockThread = new LooperThread();
mClockThread.start();
}
}