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"
);
下面,坑爹的就来了,运行发现报错:大概意思就是
if (TestJsActivity.this.mWebView.getProgress() < 100)
这行代码里的对webView的操作只能在同一个线程(犹豫其他需要,在主线程也对webView进行了操作),于是我就纠结了一天。
后来发现由于webView控件的回调方法onPageFinished()的特点,根本不需要加上面那行代码
oh,my god。知道真相的我眼泪掉下来啊。。。