如何实现100毫秒休眠的重试机制

时间:2013-05-31 12:29:06

标签: android android-layout android-intent android-listview

我想在一定毫秒后执行此指令。

我怎样才能实现这个目标?

try {
   // Get the typeface  
   MyApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
         MyApp.fontName);
   Log.d("font","in try="+MyApp.fontName);
   Log.d("font","type face="+MyApp.appTypeFace);
} 

3 个答案:

答案 0 :(得分:2)

我会使用Handler发布Runnable,如下所示:

private Runnable task = new Runnable() { 
    public void run() {
        // Execute your delayed code
    }
};

...

Handler handler = new Handler();
int millisDelay = 100;
handler.postDelayed(task, millisDelay);

代码将在postDelayed调用后100毫秒执行。

答案 1 :(得分:2)

Handler handler;

        handler=new Handler();
        Runnable notification = new Runnable() {
            @Override
            public void run() {
                MyApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
         MyApp.fontName);
   Log.d("font","in try="+MyApp.fontName);
   Log.d("font","type face="+MyApp.appTypeFace);

            }
        };
        handler.postDelayed(notification,100);

答案 2 :(得分:1)

我通常使用CountDownTimer:

http://developer.android.com/reference/android/os/CountDownTimer.html

CountDownTimer timer = new CountDownTimer(100, 100) {

     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
         //retry
         //restart with timer.start();
     }
  }.start();

但是有很多选择:AsyncTask,Threads,Runnable。

例如:

Repeat a task with a time delay?