1. 程式人生 > >Android實現延遲的幾種方法小結

Android實現延遲的幾種方法小結

本文例項總結了Android實現延遲的幾種方法。分享給大家供大家參考,具體如下:

一、通過Thread

new Thread(){
public void run(){
sleep(***);
}
}.start();

通過ProgressDialog的使用來舉例說明如下

public class A01Activity extends Activity {
 Button b;
 ProgressDialog pd;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    b=(Button)findViewById(R.id.b);
    b.setOnClickListener(new OnClickListener(){
  @Override
  public void onClick(View v) {
  // TODO Auto-generated method stub
  final CharSequence dialogTitle=getString(R.string.dialogTitle);
  final CharSequence dialogBody=getString(R.string.dialogBody);
  pd=ProgressDialog.show(A01Activity.this, dialogTitle, dialogBody, true);
  new Thread(){
   public void run(){
   try {
    sleep(3000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   finally{
    pd.dismiss();
   }
   }
  }.start();
  }
  });
  }
}

二、通過Timer

TimerTask task = new TimerTask(){
  public void run(){
  //execute the task
  }
};
Timer timer = new Timer();
timer.schedule(task, delay);

三、

new Handler().postDelayed(new Runnable(){
  public void run() {
  //execute the task
  }
 }, delay);

四、利用AlarmManager