2011-07-15 9 views

Odpowiedz

18

Użyj Handler'a i wyślij do niego prostą wiadomość lub Runnable za pomocą metody takiej jak postDelayed().

Na przykład zdefiniować obiekt Handler aby otrzymywać wiadomości i Runnables:

private Handler mHandler = new Handler(); 

Definiowanie Runnable:

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); 

     } 
    }; 

Bo te Runnable być wysłany do obsługi po upływie określonego czasu w ms :

mHandler.postDelayed(mUpdateTimeTask, 1000); 

Jeśli nie chcesz złożoności se ning a Runnable to the Handler, możesz też po prostu wysłać do niego wiadomość - nawet pustą wiadomość, dla największej prostoty - używając metody sendEmptyMessageDelayed().

+0

dzięki! Właśnie dodałem 'new Handler(). sendEmptyMessageDelayed (1, 2500);' jednak nie wiem, co to jest wartość 'int what" – austin

+2

Podany link nie jest już dostępny ... – amalBit

+0

OK, usunięto link. Myślę, że odpowiedź jest całkiem samodzielna, ponieważ wciąż jest. – Trevor

0

wywołać metodę opóźnione ze statycznego kontekście

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

W główną działalność:

@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); 
} 

Od dowolnej klasy za pomocą metody statyczne:

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 
Powiązane problemy