android延迟的几种方法

时间:2022-05-16 19:25:24

一、通过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