先來一桶理論,再來一桶源碼
有時候我們需要在某個 Activity 停留幾秒種,然後再跳到下一個
Activity。那麼這個怎麼實現呢?
一個方法是可以使用 Thread 的 sleep 函數,這個我們在 用Handler實現線程間的消息通信 也有提到:
2 |
Thread.sleep( 1 * 1000 ); |
3 |
} catch (InterruptedException
e) { |
但是這樣對於某些場合並不好,比如一個 App,打開的時候進入歡迎頁面,用 sleep 方法做停留的話,歡迎頁面可能會顯示不了的。
也可以用 Timer 來做停留。比如:
01 |
private void getHomeActivity()
{ |
02 |
Timer
timer= new Timer(); |
03 |
TimerTask
task= new TimerTask(){ |
05 |
Intent
intent = new Intent(InitActivity. this ,
MainActivity. class ); |
06 |
startActivity(intent); |
07 |
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); |
10 |
timer.schedule(task, 2500 ); |
方法一
-
new Handler().postDelayed(new Runnable() {
-
@Override
-
public void run() {
-
Intent intent = new Intent(MainActivity.this,
-
ExampleActivity.class);
-
startActivity(intent);
-
}
-
-
}, SPLASH_DISPLAY_LENGHT);
方法二
-
final Intent localIntent = new Intent(this, ExampleActivity.class);
-
Timer timer = new Timer();
-
TimerTask tast = new TimerTask() {
-
@Override
-
public void run() {
-
startActivity(localIntent);
-
}
-
};
-
timer.schedule(tast, SPLASH_DISPLAY_LENGHT);
使用範例
-
package com.app.weixin;
-
-
import java.util.Date;
-
import java.util.Timer;
-
import java.util.TimerTask;
-
-
import com.app.wexin.R;
-
-
import android.app.Activity;
-
import android.content.Intent;
-
import android.os.Bundle;
-
import android.os.Handler;
-
-
public class WelcomeActivity extends Activity{
-
-
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.welcome);
-
final Intent localIntent = new Intent(this, Tabs.class);
-
Timer timer = new Timer();
-
TimerTask tast = new TimerTask() {
-
@Override
-
public void run() {
-
startActivity(localIntent);
-
}
-
};
-
timer.schedule(tast, 1500);
-
}
-
}
此爲暫停1.5秒後跳轉。