Android Development--Play turn WebView

Source: Internet
Author: User

In Android development, network access to load a Web page requires a webview to display, which will make our app more flexible. Let's introduce some of the uses of WebView in Android today.

Basic usage

1.WebView with loading progress bar display:

Mprogressbar.setmax ( -); Mwebview.getsettings (). setjavascriptenabled (true);//Set Webviewclient to receive different notifications and requestsMwebview.setwebviewclient (NewWebviewclient () {@Override     Public Boolean shouldoverrideurlloading(WebView view, String URL) {//TODO auto-generated method stub                return false; }//Display the progress bar in the method that starts loading    @Override     Public void onpagestarted(WebView view, String URL, Bitmap favicon) {//TODO auto-generated method stub        Super. onpagestarted (view, URL, favicon);    Mprogressbar.setvisibility (view.visible); }//The progress bar is not visible in the method of ending loading    @Override     Public void onpagefinished(WebView view, String URL) {//TODO auto-generated method stub        Super. onpagefinished (view, URL);    Mprogressbar.setvisibility (view.invisible); }}); Mwebview.setwebchromeclient (NewWebchromeclient () {//Get loading progress, newprogress to 100 means load complete    @Override     Public void onprogresschanged(WebView view,intnewprogress) {//TODO auto-generated method stub        Super. onprogresschanged (view, newprogress);    Mprogressbar.setprogress (newprogress); }}); Mwebview.loadurl ("Http://m.baidu.com");

2. Intercept the loading error message:

mWebview.setWebViewClient(new WebViewClient() {   publicvoidonReceivedErrorint errorCode, String description, String failingUrl) {     "Oh no! " + description, Toast.LENGTH_SHORT).show();   } });

3. Make WebView Support scaling:

mWebView.getSettings().setBuiltInZoomControls(true);

4. Make WebView support fallback:
Through the onbackpressed method of the replication activity, if the webview can be rolled back, first call the WebView fallback method;

@OverridepublicvoidonBackPressed() {    // TODO Auto-generated method stub    ifnull && mWebView.canGoBack()) {        mWebView.goBack();    else {        super.onBackPressed();    }}
Using WebView for Java and JS interaction

1. First set up WebView support javascript:

mWebView.getSettings().setJavaScriptEnabled(true);

2. Call Java method in JS: Through WebView's Addjavascriptinterface (Object, String) method; The string value represents the class name that is called in JS.
3. Call the JS method in Java: Webview.loadurl ("javascript:+ Method name (method parameter)");
4. Note: In JS call Java method can get the return value, in Java Call JS method cannot get the return value.

Example: In the following code we first after loading completed, in Java called the JS Call_js method to display a Web Page dialog box, and then in the Web page when we click on the button will call the Java send method. The display results are as follows:

 PackageCom.example.webviewtest;ImportAndroid.annotation.SuppressLint;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.webkit.WebChromeClient;ImportAndroid.webkit.WebView;ImportAndroid.webkit.WebViewClient;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.Toast; Public  class testjsactivity extends Activity {    PrivateProgressBar Mprogressbar;PrivateWebView Mwebview;Private Static FinalString URL ="File:///android_asset/index.html";@SuppressLint({"Setjavascriptenabled","Javascriptinterface"})@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.LAYOUT.ACTIVITY_TESTJS);        Mwebview = (WebView) Findviewbyid (R.id.js_webview);        Mprogressbar = (ProgressBar) Findviewbyid (r.id.js_progress); Mprogressbar.setmax ( -); Mwebview.getsettings (). setjavascriptenabled (true); Mwebview.setwebviewclient (NewWebviewclient () {@Override             Public Boolean shouldoverrideurlloading(WebView view, String URL) {//TODO auto-generated method stub                return false; } Public void Onreceivederror(WebView view,intErrorCode, string description, String failingurl) {Toast.maketext (testjsactivity. This,"Error:"+ Description, Toast.length_short). Show (); }@Override             Public void onpagestarted(WebView view, String URL, Bitmap favicon) {//TODO auto-generated method stub                Super. onpagestarted (view, URL, favicon);            Mprogressbar.setvisibility (view.visible); }@Override             Public void onpagefinished(WebView view, String URL) {//TODO auto-generated method stub                Super. onpagefinished (view, URL); Mprogressbar.setvisibility (view.invisible);//Call JS method in Java, unable to get method return valueMwebview.loadurl ("Javascript:call_js (' Call JS in Android ')"); }        });//The Java method is called in JS, the second parameter represents the class name that is called in the JS methodMwebview.addjavascriptinterface (NewObject () { Public void Send(String message) {Toast.maketext (testjsactivity). This, message, Toast.length_short). Show (); }        },"Webviewobject"); Mwebview.setwebchromeclient (NewWebchromeclient () {@Override             Public void onprogresschanged(WebView view,intnewprogress) {//TODO auto-generated method stub                Super. onprogresschanged (view, newprogress);                Mprogressbar.setvisibility (view.visible);            Mprogressbar.setprogress (newprogress);        }        });    Mwebview.loadurl (URL); }}

JS Code:

<! DOCTYPE html><html xmlns="http://www.w3.org/1999/html"><head>    <title></title></head><body>    <input type="button" value="Webview_js" onclick ="Sendtoandroid (' call Java in JS ')"> </input>    <script type="Text/javascript">  function sendtoandroid(message){ webviewobject.send (message);        }  function call_js(message){ window.alert (message); }            </script></body></html>
Caching policies in the WebView

First, the Web cache

1. Caching Policy:
Load_cache_only: Do not use the network, only read local cache data
Load_default: Decide whether to fetch data from the network according to Cache-control.
Deprecated in Load_cache_normal:api level 17, starting from API level 11 with Load_default mode
Load_no_cache: Do not use caching, only get data from the network.
Load_cache_else_network, the data in the cache is used whenever there is a local, regardless of whether it expires, or No-cache. (If the page data changes, it still shows old data)

2. Storage location of the cache
/data/data/package_name/cache/
/data/data/package_name/database/webview.db
/data/data/package_name/database/webviewcache.db

3. Set Open cache

// 设置缓存模式mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 开启 DOM storage 功能mWebView.getSettings().setDomStorageEnabled(true);// 开启 database storage 功能mWebView.getSettings().setDatabaseEnabled(true);

4. Empty cache: Mwebview.clearcache (true); If False, only the cache in RAM is cleared.

5. Set the Cache database directory:

mWebView.getSettings().setDatabasePath(dataFilePath);

Second, H5 cache

Set up HTML5 offline cache, develop HTML offline application, need server support

1. Set Open:

mWebView.getSettings().setAppCacheEnabled(true);//允许读取文件缓存(manifest生效)mWebView.getSettings().setAllowFileAccess(true);

2. Set the maximum capacity:

mWebView.getSettings().setAppCacheMaxSize(1010241024);//10M

3. Set the cache path:

mWebView.getSettings().setAppCachePath(appCaceDir);

Websettings.setappcachepath () can only be set once for an app

4. Clear the cache:
Webstorage.getinstance (). Deleteorigin () and Webstorage.getinstance (). The Deletealldata () method appears to clear only the cache running memory and cannot delete the hard disk cache

Delete the cache path folder directly to clean up the hard disk cache.

Keep the cookies in the WebView app in the login state

Refer to the following blog post: Understanding of cookies and session

Android Development--Play turn WebView

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.