Android 延时执行任务的三种简单方法

时间:2023-01-28 07:52:04
  1. 开启一个新的线程
      new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        Thread.sleep(2000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    startActivity(new Intent(LeadActivity.this, WelcomeActivity.class));
                                }
                            }.start();
    

      

  2. handler 加 postDelayed 
     handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    startActivity(new Intent(LeadActivity.this, WelcomeActivity.class));
                                }
                            },3000);
                        }
    

      

  3. 定时器  TimerTask  和 Timer
     TimerTask task = new TimerTask() {
                                @Override
                                public void run() {
                                    startActivity(new Intent(LeadActivity.this, WelcomeActivity.class));
                                }
                            };
                            Timer timer = new Timer();
                            timer.schedule(task,1000);
                        }