public void onCreate(Bundle savedInstanceState) { |
super .onCreate(savedInstanceState); |
setContentView(R.layout.main); |
mTextView = (TextView) findViewById(R.id.myTextView); |
mHandler = new Handler() { |
public void handleMessage(Message msg) { /* 这里是处理信息的方法 */ |
switch (msg.what) { |
case 123 : /* 在这处理要TextView对象Show时间的事件 */ |
mTextView.setText(mHour + " : " + mMinutes); |
break ; |
} |
super .handleMessage(msg); |
} |
}; |
mClockThread = new LooperThread(); |
mClockThread.start(); |
} |
class LooperThread extends Thread { |
public void run() { |
super .run(); |
try { |
do { /* 取得系统时间 */ |
long time = System.currentTimeMillis(); /* 透过Calendar对象来取得小时与分钟 */ |
final Calendar mCalendar = Calendar.getInstance(); |
mCalendar.setTimeInMillis(time); |
mHour = mCalendar.get(Calendar.HOUR); |
mMinutes = mCalendar.get(Calendar.MINUTE); /* 让线程休息一秒 */ |
Thread.sleep( 1000 ); /* 重要关键程序:取得时间后发出讯息给Handler */ |
Message m = new Message(); |
m.what = 123 ; |
EX04_14. this .mHandler.sendMessage(m); |
} while (EX04_14.LooperThread.interrupted() == false ); /* 当系统发出中断讯息时停止本循环 */ |
} catch (Exception e) { |
e.printStackTrace(); |
} |
} |
} |