---
title: "Splash界面简单实现"
author: "stchou"
date: "2012-02-21T23:12:23Z"
tags: []
categories: ["移动开发"]
slug: "splash"
draft: false
lastmod: "2012-02-21T23:12:23Z"
id: 1416040
url: "https://stchou.iteye.com/blog/1416040"
---

**Splash界面简单实现**

大家都知道，android的应用很多的开始都是有一个Splash界面，

如：

![](http://dl.iteye.com/upload/attachment/0063/5634/bedb00c1-a83c-3a13-8cc4-43f510da4b6d.jpg)

实现起来其实很简单

 

实现原理： 

 

    通过Timer和TimerTask,Handler的结合。Timer来计时，TimerTask来判断是不是已经满足设定时间,hanlder来具体启动新的Activity。

![](http://dl.iteye.com/upload/attachment/0063/5631/fa582476-ac8f-37be-b696-f1272e37e978.jpg)  
 

&lt;!--EndFragment--&gt;

```
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;

public class SplashActivity extends Activity {
	private long startTime;
	private boolean touched=false;
	private Timer timer ;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.splash);
		//开启 定时器
		timer = new Timer(true);
		startTime = System.currentTimeMillis();
		timer.schedule(task, 0, 1);
	}

	
	private final TimerTask task = new TimerTask() {
		public void run() {
			if (task.scheduledExecutionTime() - startTime == 2000 || touched) {
				Message message = new Message();
				message.what = 0;
				timerHandler.sendMessage(message);
				timer.cancel();
				this.cancel();
			}

		}
	};

	private final Handler timerHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				SplashActivity.this.finish();
				// 跳转到新的 activity
				Intent intent = new Intent(SplashActivity.this,TabMain.class);
				SplashActivity.this.startActivity(intent);
				
				
				break;
			}
			super.handleMessage(msg);
		}
	};

	
	/**
	 * 点击直接跳转
	 */
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			touched = true;
		}
		return true;
	}
}
```