我只想說:what a fucking day!java
今天要作一個webView的超時功能,因而開始百度,一看貌似很簡單啊,因而開始copy了下面的代碼。android
import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Window; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class TestJsActivity extends Activity { private long timeout = 5000; private WebView mWebView; private Handler mHandler = new Handler(); private Timer timer; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setAllowFileAccess(true); mWebView.setWebViewClient(new WebViewClient() { /* * 建立一個WebViewClient,重寫onPageStarted和onPageFinished * * * onPageStarted中啓動一個計時器,到達設置時間後利用handle發送消息給activity執行超時後的動做. * */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.d("testTimeout", "onPageStarted..........."); // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); timer = new Timer(); TimerTask tt = new TimerTask() { @Override public void run() { /* * 超時後,首先判斷頁面加載進度,超時而且進度小於100,就執行超時後的動做 */ if (TestJsActivity.this.mWebView.getProgress() < 100) { Log.d("testTimeout", "timeout..........."); Message msg = new Message(); msg.what = 1; mHandler.sendMessage(msg); timer.cancel(); timer.purge(); } } }; timer.schedule(tt, timeout, 1); } /** * onPageFinished指頁面加載完成,完成後取消計時器 */ @Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub super.onPageFinished(view, url); Log.d("testTimeout", "onPageFinished+++++++++++++++++++++++++"); Log.d("testTimeout", "+++++++++++++++++++++++++" + TestJsActivity.this.mWebView.getProgress()); timer.cancel(); timer.purge(); } }); mWebView.loadUrl("http://image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=index&pv=&z=0&word=%D7%C0%C3%E6&s=0"); } }
下面,坑爹的就來了,運行發現報錯:大概意思就是web
if (TestJsActivity.this.mWebView.getProgress() < 100)這行代碼裏的對webView的操做只能在同一個線程(猶豫其餘須要,在主線程也對webView進行了操做),因而我就糾結了一天。後來發現因爲webView控件的回調方法onPageFinished()的特色,根本不須要加上面那行代碼oh,my god。知道真相的我眼淚掉下來啊。。。