Android has a deep understanding of WebView -- androidwebview
Summary
As Android Developers, we all know that a high-performance webkit kernel browser is built in the mobile phone and encapsulated as a WebView component in the SDK. Today we will talk about how to use WebView in Android.
This article is original, reprint please note address: http://blog.kymjs.com/
As Android Developers, we all know that a high-performance webkit kernel browser is built in the mobile phone and encapsulated as a WebView component in the SDK.
Pay attention to the following points during development:
1. This is the most basic AndroidManifest. xml file that requires network access permissions.
2. If the accessed page contains Javascript, WebView must be set to support Javascript.
WebView.getSettings().setJavaScriptEnabled(true);
3. If you want to click the link on the page to continue responding to the current browser, instead of opening the Android system browser, you must overwrite the WebViewClient object of WebView.
mWebView.setWebViewClient(new WebViewClient(){public boolean shouldOverrideUrlLoading(WebView view, String url){ view.loadUrl(url);return true;}});
4. if you do not do any processing, browse the Web page and click the system "Back" key, the entire Browser will call finish () to end itself. If you want to browse the Web page Back rather than launch the Browser, the Back event needs to be processed and consumed in the current Activity. (code is simplified)
public boolean onKeyDown(int keyCode, KeyEvent event) {if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack();return true;}return super.onKeyDown(keyCode, event);}Interaction with js
Since the webpage can be displayed, you can also perform local operations on the webpage. (I adjusted the indentation because one row cannot be written)
public class WebViewDemo extends Activity { private WebView mWebView;private Handler mHandler = new Handler(); public void onCreate(Bundle icicle) { setContentView(R.layout.WebViewdemo);mWebView = (WebView) findViewById(R.id.WebView); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new Object() { public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); }}, "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); }}
The addJavascriptInterface (Object obj, String interfaceName) method binds a java Object to a javascript Object. The javascript Object Name Is interfaceName (demo) and the scope is Global. after WebView initialization, you can directly use javascript: window. the demo has accessed the bound java object. let's see how html is called.
In this way, the clickOnAndroid () method of the java object can be called in javascript. We can also define many methods in this object (such as sending text messages, calling contact lists and other mobile phone system functions ), here, the wave () method is an example of calling javascript in java.
Note: The Java object and method to be bound in the addJavascriptInterface method must run in another thread and cannot be run in the Construction thread. This is also the purpose of using Handler.
In-depth use of WebView for js to call Android code
First, briefly describe the differences among WebView, WebViewClient, and WebChromeClient:
In the design of WebView, The WebView class is not required to do anything. Some chores are assigned to others, so that WebView can focus on parsing and rendering. webViewClient is used to help WebView process various notifications and request events. WebChromeClient is used to assist WebView in processing Javascript dialogs, website icons, and website titles.
Function implementation:
Use WebView in android to load an html webpage, define a button in the html webpage, and click the button to bring up a toast.
Steps:
First, define an interface class, pass context objects in, and define the methods to be implemented in js in the interface class.
Next, define an html file under the assets resource package, and define a button. button click event in the file as a js function.
Then define a WebView component in xml, obtain WebView in the activity class, and set WebView parameters, pay special attention to setting WebView to support js and add the defined js interface class to WebView. Then, you can use the functions defined in this interface class in js. that is:
MyWebView. getSettings (). setJavaScriptEnabled (true );
MyWebView. addJavascriptInterface (new JavaScriptinterface (this), "android ");
Finally, the method for loading a local html file using WebView is as follows:
myWebView.loadData(htmlText,"text/html", "utf-8");
Htmltext reads the content in html in assets as a string.
4. Use the return key to return to the previous page:
Set the WebView button listening, listen to the expired return key, and determine whether the webpage can be returned. The WebView goBack () is used to return to the previous page.
WebView Cache
If the WebView control is used in the project, when the html page is loaded, two folders, database and cache, will be generated under the/data/package name directory (my mobile phone has no root, ).
The requested url record is saved in WebViewCache. db, And the url content is saved in the WebViewCache folder. you can define an html file, display an image in it, load it with WebView, and then try to read the image from the cache and display it.
WebView deletion Cache
As a matter of fact, you already know the location where the cache is saved, so it is easy to delete it. You can just get the cache and delete it.
// Delete the cache stored on the mobile phone
private int clearCacheFolder(File dir,long numDays) { int deletedFiles = 0; if (dir!= null && dir.isDirectory()){ try { for (File child:dir.listFiles()){ if (child.isDirectory()) { deletedFiles += clearCacheFolder(child, numDays); } if (child.lastModified() < numDays) { if (child.delete()) { deletedFiles++; } } } } catch(Exception e) { e.printStackTrace(); } } return deletedFiles; }
Whether to enable the cache function is also controllable
// Cache is used first: WebView. getSettings (). setCacheMode (WebSettings. LOAD_CACHE_ELSE_NETWORK); // No cache is used: WebView. getSettings (). setCacheMode (WebSettings. LOAD_NO_CACHE );
Add the following code when exiting the application to clear the cache.
File file = CacheManager.getCacheFileBaseDir();if (file != null && file.exists() && file.isDirectory()) { for (File item : file.listFiles()) { item.delete();}file.delete(); }context.deleteDatabase("WebView.db"); context.deleteDatabase("WebViewCache.db");WebView handles Error 404
A problem occurs when displaying a Web page, that is, the web page may not be found, and WebView can also be handled. (if there are too many codes, only the important part will be posted here)
Public class WebViewActivity extends Activity {private Handler handler = new Handler () {public void handleMessage (Message msg) {if (msg. what = 404) {// The home page does not exist // load the error message page 404.html web under the local assets folder. loadUrl ("file: // android_asset/404.html");} else {web. loadUrl (HOMEPAGE) ;}};@ Override protected void onCreate (Bundle savedInstanceState) {web. setWebViewClient (new WebViewClient () {public boolean shouldOverrideUrl (WebView view, String url) {if (url. startsWith ("http: //") & getRespStatus (url) = 404) {view. stopLoading (); // load the error message page 404.html view under the local assets folder. loadUrl ("file: // android_asset/404.html");} else {view. loadUrl (url) ;}return true ;}}); new Thread (new Runnable () {public void run () {Message msg = new Message (); // determine whether the home page exists here, because the home page is loaded through loadUrl. // at this time, shouldOverrideUrlLoading is not executed to determine whether the page exists. // after entering the home page, click the link in the home page, link to other pages and the shouldOverrideUrlLoading method will be executed. if (getRespStatus (HOMEPAGE) = 404) {msg. what = 404;} handler. sendMessage (msg );}). start ();}}Unfinished
Because WebView is used too much, it is divided into two parts. The next part describes the WebView rolling status monitoring and the method for obtaining session and writing cookies ~~