Handler实现2秒自动切图

package com.lilin.handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

/**
 * 通过Handler实现2秒自动换图
 * 
 * @author lilin
 * @date 2011-8-10 上午08:51:27
 * @ClassName: Main
 * @Description: TODO
 */
public class Main extends Activity {
	ImageView myImageView;// ImageView的引用

	public void onCreate(Bundle savedInstanceState) {// 重写的onCreate方法
		super.onCreate(savedInstanceState);
		setTitle("handler通信:每2秒自动换图");
		setContentView(R.layout.main);// 设置当前的用户界面

		
		System.out
				.println("当前activity的ID--->" + Thread.currentThread().getId());
		System.out.println("当前activity的名称--->"
				+ Thread.currentThread().getName());

		myImageView = (ImageView) findViewById(R.id.myImageView);

		new Thread() {
			public void run() {
				int i = 0;
				while (true) {// 循环
					myHandler.sendEmptyMessage((i++) % 4);// 发送消息
					System.out.println("handler的ID--->"
							+ Thread.currentThread().getId());
					System.out.println("handler的名称--->"
							+ Thread.currentThread().getName());
					try {
						Thread.sleep(2000);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			};
		}.start();
	}

	Handler myHandler = new Handler() {// 创建一个Handler对象
		public void handleMessage(Message msg) {// 重写接收消息的方法
			switch (msg.what) {// 判断what的值
			case 0:// what值为0时
				myImageView.setImageResource(R.drawable.bbta);
				break;
			case 1:// what值为1时
				myImageView.setImageResource(R.drawable.bbtb);
				break;
			case 2:// what值为2时
				myImageView.setImageResource(R.drawable.bbtc);
				break;
			case 3:// what值为3时
				myImageView.setImageResource(R.drawable.bbtd);
				break;
			}
			super.handleMessage(msg);
		}
	};
}

相关推荐