在进入程序前,一般都要有一个欢迎图片LOGO或者动画,等待几秒后隐藏Logo或做Intent跳转:
可以使用HandlerThread新建一个线程来执行等待动作,也可以使用Android的TimerTask:
1.HandlerThread:
- public class WelcomeAct extends Activity {
- protected static final String TAG = "WelcomeAct";
- private Handler handler; //因为要重写构造方法,所以不能用匿名内部类
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // 设置登录无标题栏
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.welcome);
- HandlerThread myThread = new HandlerThread("myHandlerThread");
- myThread.start();
- handler = new myHandler(myThread.getLooper());
- handler.post(new Runnable() {
- @Override
- public void run() {
- try {
- //耗时的操作
- Thread.sleep(2500);
- //handler主要用于异步消息的处理,使用sendMessage()后,方法立即返回,Message放入消息队列,
- //等待Message出消息队列,由handlerMessage(Message msg)通知UI线程子线程已经挂起,并使用返回的msg。
- handler.sendMessage(handler.obtainMessage());
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- });
- }
- class myHandler extends Handler{
- public myHandler(Looper looper) {
- super(looper);
- }
- //负责从消息队列中取消息给UI线程
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- Intent intent = new Intent(WelcomeAct.this, LoginAct.class);
- startActivity(intent);
- }
- }
- }
2.使用TimerTask:
- public class WelcomeAct extends Activity {
- protected static final int LOGINOVER = 0;
- protected static final String TAG = "WelcomeAct";
- private Handler handler; //因为要重写构造方法,所以不能用匿名内部类
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // 设置登录无标题栏
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.welcome);
- ProgressBar loading = (ProgressBar)findViewById(R.id.loading);
- loading.setVisibility(View.VISIBLE);
- HandlerThread myThread = new HandlerThread("myHandlerThread");
- myThread.start();
- handler = new Handler(){
- @Override
- public void handleMessage(Message msg) {
- if(msg.what == LOGINOVER){
- Log.i(TAG, Thread.currentThread().getName());
- Intent intent = new Intent(WelcomeAct.this, LoginAct.class);
- startActivity(intent);
- }
- }
- };
- tt.run();
- }
- TimerTask tt = new TimerTask() {
- @Override
- public void run() {
- Log.i(TAG, Thread.currentThread().getName());
- handler.sendMessageDelayed(handler.obtainMessage(LOGINOVER), 3000);
- }
- };
- }
也可设计为没有Intent跳转,使用View.setVisibility(View.GONE);和 View.VISIBLE来达到想要的效果。
使用TimerTask,打印线程名可以看出,系统没有新开线程,而且达到了阻塞等待的目的,代码量小,推荐用。