码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-01-25 16:42:11      阅读:202      评论:0      收藏:0      [点我收藏+]

标签: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() {

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

	}

}
运行实例如下:

技术分享

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

标签:android   handler   

原文地址:http://blog.csdn.net/yayun0516/article/details/43115219

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!