首页 > 代码库 > 安卓--子线程和主线程之间的交互实例(时钟)

安卓--子线程和主线程之间的交互实例(时钟)

.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() {

		@Override
		public 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();//启动线程

	}

}
运行实例如下:

技术分享

安卓--子线程和主线程之间的交互实例(时钟)