webview--网络超时
- package com.test.js2java;
- 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");
- }
- }
其中要注意的是onPageFinished的两点,第一点,官方是这样解释的:
Notify the host application that a page has finished loading. This method is called only for main frame. When onPageFinished() is called, the rendering picture may not be updated yet. To get the notification for the new Picture, use onNewPicture(WebView, Picture)
.
也就是说,程序只认为DOM加载完成就完成了,正在加载的图片不在这个范围之内。
第二点是,如果在JS文件中又动态去加载另一JS,onPageFinished方法会在所有的JS全部加载完毕后才调用。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。