先来一桶理论,再来一桶源码
有时候我们需要在某个 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秒后跳转。