Examples of the interaction between the [sub] Android thread and the main thread (clock)

.xml code is as follows:

<?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 code is as follows:

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

Run the examples are as follows:
Here Insert Picture Description

Published 73 original articles · won praise 17 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40110781/article/details/104955679