2011-11-21 58 views

回答

8

首先,你需要創建一個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(); 
      } 
     }); 
    } 
} 

在你的活動,你可以用這條線:當應用程序

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

這是否計時器將僅運行活性?或用戶正在看到用戶界面? – Shan

+0

只有當活動被殺死時,這個計時器才被殺死;如果它是活動的,用戶是否可以看到它,它是否在後臺,這個定時器工作。您可以修改run()方法中第一個'if'的行爲 –