2011-07-15 51 views

回答

18

使用Handler,並使用諸如postDelayed()之類的方法向其發送簡單消息或Runnable。

例如,定義一個Handler對象接收消息和的Runnable:

private Handler mHandler = new Handler(); 

定義一個可運行:

private Runnable mUpdateTimeTask = new Runnable() { 
    public void run() { 
     // Do some stuff that you want to do here 

    // You could do this call if you wanted it to be periodic: 
     mHandler.postDelayed(this, 5000); 

     } 
    }; 

原因的可運行以在指定的延遲後在ms被髮送到處理程序:

mHandler.postDelayed(mUpdateTimeTask, 1000); 

如果你不想複雜的se向處理程序發送Runnable,您也可以非常簡單地發送消息給它 - 即使是空的消息,爲了最簡單 - 使用方法sendEmptyMessageDelayed()

+0

的感謝!我只是添加了新的Handler()。sendEmptyMessageDelayed(1,2500);'但是我不知道'int什麼'值代表 – austin

+2

您提供的鏈接不再可用... – amalBit

+0

好吧,鏈接已刪除。我認爲答案是相當獨立的,因爲它仍然是。 – Trevor

0

呼叫延遲的方法從靜態上下文

public final class Config { 
    public static MainActivity context = null; 
} 

MainActivity

@Override 
protected void onCreate(final Bundle savedInstanceState) { 
    ... 
    Config.context = this; 
    ... 
} 

... 

public void execute_method_after_delay(final Callable<Integer> method, int millisec) 
{ 
    final Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       method.call(); 
      } 
      catch (Exception e) { 

      } 
     } 
    }, millisec); 
} 

使用任何類的靜態方法

private static void a_static_method() 
{ 

    int delay = 3000; 
    Config.context.execute_method_after_delay(new Callable<Integer>() { 
     public Integer call() { 
      return method_to_call(); 
     } 
    }, delay); 


} 

public static Integer method_to_call() 
{ 
    // DO SOMETHING