2011-07-15 49 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