创建一个android的Splash Screen

fmms 12年前
     <p>在开发android应用的时候 ,尤其是游戏的时候,经常需要有一个Splash Screen(就类似于Eclipse启动的画面)。但是,android好像没有对这个有很好的支持(也许我没找到吧)。比如iphone,只需要将 Splash的图片以default命名,就可以可以出现Splash Screen了,方式很简单。那在android中怎么办呢?我试了两种方法,下面我给大家一一道来。</p>    <p>第一种,我采用的方式是在Activity中新开一个线程,这个线程判断过去了多长时间,如果到大了设定的时间,则结束当前的Splash Screen,启动新的Activity,往往是游戏的主菜单。这种方式表面上使用没有任何的问题,但是,当我结束线程的使用stop方法的时候,android实际上跑出了一个异常:不支持这个操作。尽管能够运行,但是有异常,有点不爽。所以我就改造了一下,使用了第二种方法。</p>    <p>第二种,通过Timer和TimerTask,Handler的结合。Timer来计时,TimerTask来判断是不是已经满足设定时间,hanlder来具体启动新的Activity。这种方法比较好,没有出现异常。具体的实现方法:</p>    <p>在Activity中的onCreate方法中,初始化并开始Timer:</p>    <pre class="brush:java; toolbar: true; auto-links: false;">timer = new Timer(true); startTime = System.currentTimeMillis(); timer.schedule(task, 0, 1);</pre>startTime是开始时间,要判断时间差是否满足设定的时间。下面是TimerTask的代码:    <pre class="brush:java; toolbar: true; auto-links: false;">private final TimerTask task = new TimerTask() {                 @Override                 public void run() {                        if (task.scheduledExecutionTime() - startTime == 1000 || !_active) {                                          Message message = new Message();                                             message.what = 0;                                          timerHandler.sendMessage(message);                                          timer.cancel();                                          this.cancel();                                       }                  }         };</pre>还有handler的代码:    <pre class="brush:java; toolbar: true; auto-links: false;">private final Handler timerHandler = new Handler() {                 public void handleMessage(Message msg) {                         switch (msg.what) {                case 0:                                  SplashScreen.this.finish();                         //start new activity here                     break;                         }                            super.handleMessage(msg);                    }         };</pre>    <p></p>    <p>这样一个基本的Splash就实现了。</p>    <p>另外,不知道大家发现没有,我的代码中有一个这个_active变量,这个是做什么的呢?见下面的代码:</p>    <pre class="brush:java; toolbar: true; auto-links: false;">@Override     public boolean onTouchEvent(MotionEvent event) {         if (event.getAction() == MotionEvent.ACTION_DOWN) {             _touched = false;         }         return true;     }</pre>    <p></p>    <p>在显示Splash Screen的过程中,如果触摸了屏幕,会直接跳过Splash Screen的,给用户以更高的体验。</p>    <p>没有更深入研究,欢迎大家讨论。</p>    <p>文章出处:<a href="/misc/goto?guid=4959499213135052368" rel="nofollow">http://www.eoeandroid.com/thread-8225-1-1.html</a></p>    <p></p>    <p></p>