標籤:android handler
.xml代碼如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <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" android:text="" /></LinearLayout>
.java程式碼如下:
package org.lxh.demo;import java.util.Date;import java.text.SimpleDateFormat;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.widget.TextView;public class Hello extends Activity {private TextView info = null;private static final int SET = 1;private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case SET:Hello.this.info.setText("目前時間為:" + msg.obj.toString());break;}}};private class ClockThread implements Runnable {//顯示時間的線程類public void run() {while (true) {try {Message msg = Hello.this.handler.obtainMessage(Hello.SET,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));Hello.this.handler.sendMessage(msg);Thread.sleep(1000);} catch (Exception e) {}}}}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();//啟動線程}}運行執行個體如下:
安卓--子線程和主線程之間的互動執行個體(時鐘)