2011-11-21 8 views

risposta

8

Prima di tutto, è necessario creare una classe TimerTask:

protected class ReloadWebView extends TimerTask { 
    Activity context; 
    Timer timer; 
    WebView wv; 

    public ReloadWebView(Activity context, int seconds, WebView wv) { 
     this.context = context; 
     this.wv = wv; 

     timer = new Timer(); 
     /* execute the first task after seconds */ 
     timer.schedule(this, 
       seconds * 1000, // initial delay 
       seconds * 1000); // subsequent rate 

     /* if you want to execute the first task immediatly */ 
     /* 
     timer.schedule(this, 
       0,    // initial delay null 
       seconds * 1000); // subsequent rate 
     */ 
    } 

    @Override 
    public void run() { 
     if(context == null || context.isFinishing()) { 
      // Activity killed 
      this.cancel(); 
      return; 
     } 

     context.runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       wv.reload(); 
      } 
     }); 
    } 
} 

nella vostra attività, è possibile utilizzare questa linea:

new ReloadWebView(this, 60, wv); 
+0

Se questo timer sarebbe stato solo in esecuzione quando l'applicazione è attivo? o l'utente sta vedendo l'interfaccia utente? – Shan

+0

Questo timer viene ucciso solo quando l'attività viene uccisa; se è attivo, se l'utente può vederlo, sia che si trovi in ​​background, questo timer funziona. È possibile modificare questo comportamento lavorando sul primo 'if' nel metodo run() –

Problemi correlati