安卓--子線程和主線程之間的互動執行個體(時鐘)
.xml代碼如下:
.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();//啟動線程}}運行執行個體如下: