Android webview usage and common Exception Handling

Source: Internet
Author: User
Tags blank page

The webview control provided in Android allows developers to embed their own applications into the web browsing function, but some problems may occur in actual development. This will be introduced later,

:

Let's first look at an instance:

public class MainActivity extends Activity {final String COMPANY_WEB="http://www.csdn.net";private WebView mWebView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mWebView = (WebView) findViewById(R.id.webview);setWebView();}private void setWebView(){WebSettings webSettings = mWebView.getSettings();  webSettings.setJavaScriptEnabled(true);        webSettings.setAllowFileAccess(true);        webSettings.setBuiltInZoomControls(true);    webSettings.setPluginsEnabled(true);mWebView.setWebViewClient(new MonitorWebClient());mWebView.loadUrl(COMPANY_WEB);}private class MonitorWebClient extends WebViewClient{@Overridepublic void onPageStarted(WebView view, String url, Bitmap favicon) {super.onPageStarted(view, url, favicon);}@Overridepublic void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);}@Overridepublic boolean shouldOverrideUrlLoading(WebView view, final String url) {String website=Uri.parse(url).getHost();if (COMPANY_WEB.equals(website)) {            // This is my web site, so do not override; let my WebView load the page            return false;      }else{ view.loadUrl(url);                           return true;  }//return super.shouldOverrideUrlLoading(view, url);}}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event){    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())    {        mWebView.goBack();        return true;    }    return super.onKeyDown(keyCode, event);}}

Related permissions:

<uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

OK, test the relevant link can also appear normal access, the above is the csdn website as an example, if the site is changed to http://www.qq.com also no problem, click the navigation bar can also be accessed normally, then click the image connection to display eventhub. removemessages (INT what = 107) is not supported before the webviewcore is set up exception information. Some people say it is not starting with http: //. I tried it and did not solve the problem, someone is expected to solve this problem. When I click the relevant news link on the homepage, a blank page is displayed and cannot be accessed normally. Later, I found that this is related to the website structure. It seems that webview does not fully implement the browser function.

The next step is simple exception handling, which is mainly to rewrite the onreceivederror () method and onreceivedsslerror () method in the webviewclient class for processing.

After the exception is simply handled, let's talk about how to speed up Website access, especially with a large number of flash, SWF animation and various CSS style functions. At this time, we should use cache, you can set the cache size and the appropriate mode to optimize the webview. You can set the following two modes:

1. load_default: determines whether to retrieve data from the Network Based on Cache-control.
2. load_cache_else_network: Data in the cache is used no matter whether it expires or not.
For example, m.taobao.com's cache-control is no-Cache. In the load_default mode, data is retrieved from the network in any case. If there is no network, an error page is displayed; in load_cache_else_network mode, cache is used no matter whether the network exists or not.
M.sina.com.cn's cache-control is Max-age = 60, and local cache data is used in both modes.

Conclusion: Based on the above two modes, the cache policy is recommended to determine whether a network exists. If yes, load_default is used. If no network exists, load_cache_else_network is used.

Let's take a look at the optimized code:

Public class mainactivity extends activity {final string company_web = "http://www.deczh.com/"; private webview mwebview; private context activity; // Private progressdialog; // history Web site // Private stack <string> webhistory = new stack <string> (); @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); mwebview = (Webview) findviewbyid (R. id. webview); setwebview (); Activity = This; mhandler. sendemptymessagedelayed (0, 1000);} private void setwebview () {websettings = mwebview. getsettings (); // Java Script websettings. setjavascriptenabled (true); websettings. setjavascriptcanopenwindowsautomatically (true); // access assets and resources websettings. setallowfileaccess (true); // zoom page websettings. setbuilti Nzoomcontrols (true); websettings. setpluginsenabled (true); // set xml dom cache websettings. setdomstorageenabled (true); // improves the rendering priority by websettings. setrenderpriority (renderpriority. high); // set cache string appcachepath = getdir ("netcache", context. mode_private ). getabsolutepath (); websettings. setappcacheenabled (true); websettings. setappcachepath (appcachepath); websettings. setappcachemaxsize (1024*1024*5 ); Websettings. setcachemode (websettings. load_cache_else_network); mwebview. setwebviewclient (New monitorwebclient (); mwebview. setwebchromeclient (New appcachewebchromeclient ();} private class monitorwebclient extends webviewclient {@ overridepublic void onreceivederror (webview view, int errorcode, string description, string failingurl) {// error message: Toast = toast. maketext (getbasecontext (), "Oh no! "+ Description, toast. length_long); toast. setgravity (gravity. top | gravity. center, 0, 0); toast. show (); // error handling try {mwebview. stoploading ();} catch (exception e) {}try {mwebview. clearview ();} catch (exception e) {} If (mwebview. cangoback () {mwebview. goback ();} // super. onreceivederror (view, errorcode, description, failingurl);} // when loading an HTTPS page with an SSL layer, if the security certificate of this Website Cannot be authenticated on Android, webview will become a blank Does not pop out a risk prompt box @ overridepublic void onreceivedsslerror (webview view, sslerrorhandler handler, sslerror error) as in the PC browser) {// ignore the certificate error. Continue to load the page content handler. proceed (); // handler. cancel (); // default Android processing method // handlemessage (Message MSG); // perform other processing // super. onreceivedsslerror (view, handler, error) ;}@ overridepublic void onpagestarted (webview view, string URL, bitmap favicon) {/* If (progressdialog = NULL) {// If No progress dialog, make one and Set message progressdialog = new progressdialog (activity); progressdialog. setmessage ("loading please wait... "); progressdialog. show (); // hide the webview while loading mwebview. setenabled (false);} * // super. onpagestarted (view, URL, favicon) ;}@ overridepublic void onpagefinished (webview view, string URL) {/* If (progressdialog! = NULL & progressdialog. isshowing () {progressdialog. Dismiss (); progressdialog = NULL; mwebview. setenabled (true);} * // * If (! Webhistory. contains (URL) webhistory. push (URL); * // super. onpagefinished (view, URL) ;}@ overridepublic Boolean shouldoverrideurlloading (webview view, final string URL) {log. E (getclass (). getsimplename (), "website =" + URL); // string website = Uri. parse (URL ). gethost (); string processurl = URL; If (! Processurl. startswith ("http: //") processurl = "http: //" + processurl; If (company_web.equals (URL) {// This is my Web site, so do not override; let my webview load the page return false;} else {view. loadurl (processurl); Return true;} // return Super. shouldoverrideurlloading (view, URL) ;}} private class appcachewebchromeclient extends webchromeclient {@ override public void onreachedmaxappcachesize (long Spaceneeded, long totalusedquota, webstorage. quotaupdater) {// log. E (app_cache, "onreachedmaxappcachesize reached, increasing space:" + spaceneeded); quotaupdater. updatequota (spaceneeded * 2);} private Boolean pause = false; @ overridepublic void onpause () {super. onpause (); If (mwebview! = NULL) {mwebview. pausetimers (); mwebview. onpause (); this. pause = true ;}@ overridepublic void onresume () {super. onresume (); If (mwebview! = NULL & pause) {mwebview. resumetimers (); mwebview. onresume (); this. pause = false ;}@ overridepublic Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_back) & mwebview. cangoback () {mwebview. goback (); Return true;} return Super. onkeydown (keycode, event );}}

Related permissions:

<uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

After code optimization, the access speed is significantly improved, and some errors are handled, but exceptions still cannot be handled. If anyone has a good error handling method, I hope you can leave a message to discuss it and make progress together.

Let's talk about it first!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.