WebView Usage Summary

Source: Internet
Author: User
Tags custom name

WebView Use summary gossip (you can directly ignore

Long time has not been on the blog to write something, summed up the recent learning situation, but also the curriculum design is the project, are quickly made into XX. Recently took a pot, to do a social travel application, the content of the travels by the user editor and then to the server, by the front-end to write a different template after the picture into the template, the previous paragraph is still very slip, The templates are pretty good (shooting chicken wet is also very bad, Android side need to browse through the webview to the already processed travels. First contact to the WebView, feel good excited good mysterious, the following will use WebView some experience to everyone on the Orz. For a long time did not come up to write something, one up on the big crap (

1. Introduction

International practice, first look at Google to sell its own things.

PublicclassWebView extends Absolutelayout implements Viewtreeobserver.onglobalfocuschangelistener Viewgroup.onhierarchychange    Listenerjava.lang.Object?    Android.view.View?    Android.view.ViewGroup?    Android.widget.AbsoluteLayout? Android.webkit.WebView A View thatDisplays Web pages. Thisclass  is  theBasis upon which you can roll your own web browserorSimply displaysomeOnline content within your Activity. It uses theWebKit Rendering Engine toDisplay Web pages andIncludes methods toNavigate Forward andBackwardthroughA history, zoominch  andOut, performtextSearches andMore. Note that,inchOrder forYour Activity toAccess theInternet andLoad Web pagesinchA WebView, you must add theINTERNET Permissions toYour Android Manifestfile: <uses-permission android:name="Android.permission.INTERNET"/> attached my residue translation orz:webview is a control that is used to display Web pages, which can be used as a basis for you to make your own browser or just display some content on the web in activity.    It uses the WebKit rendering engine to display Web pages and to display the previous and next pages in the history, shrink and query the text on the page. It should be noted that in order for WebView to access the network, the following permissions should be added to the Androidmanifest.xml file (the line above) ..... If the direct access to the local HTML, is not added, but the local have what fun, it is best to add, forget the game OverThe

Plainly is used to display the Web page, before the small tatsu only know what to access the Internet, do not know that you can also access the local HTML file, the following will be presented to everyone.

2. Simple to use

I know about it.

2.1 Loading from the network

At the very beginning, it was written in the official document.

webview.loadUrl("http://slashdot.org/");

See this moment stunned, just think so wrong. Can you access the website by passing in the URL? Then try it, create an activity, and put only one webview in the layout file:

<relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools"android:id="@+id/activity_display _template_root "android:layout_width=" Match_parent "android:layout_height= "Match_parent" Tools:context="com.ldx.microtravelnotes.ui.activity.DisplayTemplateActivity">                                                                                    <WebViewandroid:id= "@+id/webview"android:layout_width="Match_ Parent "android:layout_height=" match_parent "/>                        </relativelayout>

Turn to activity inside the webview to set, need to explain is, direct mwebview.setxxx () What can not find, what also can not set, webview inside there is a websetting, equivalent to configure the current WebView of a class , which can be set to support JavaScript and other content, others to explore the .....

mWebView.getSettings().setJavaScriptEnabled(true);mWebView.getSettings().setAllowFileAccessFromFileURLs(true);mWebView.loadUrl("http://www.baidu.com");

After that I found that it is really such a drawback (not pictured you bb),:

Key points in Loadurl this function, the above example will be Baidu's URL to WebView loading, can directly browse Baidu's home page, but also can not achieve browser-like click, those need further processing. loading content from the network there is no pit, it is important to remember to add the permissions of the application, remember to configure the websetting on it.

2.2 Loading from local

Contact with the initial use of WebView, the small Tatsu soon and the front-end, the success of the display of the front-end production effect, the previous picture, the way the Great God for Light spray Orz:

After that, however, some templates (html,css,js) need to be previewed after downloading from the server to local. Also involves the WebView loading local files, in the implementation of the process encountered a number of pits, presented to share with you. The layout file is also the same as above. XML unchanged. The only thing that needs to change is the URL passed to WebView, which is changed to get the local file.

mWebView.loadUrl("file:///android_assert/demo.html");

Demo.html is just an HTML file placed under the asserts Resource folder, as follows:

<html><head>    <script type="Text/javascript">  function updatehtml(){ document.getElementById ("Content"). InnerHTML = "You have invoke JavaScript method";}</script></head><body>This is my HTML<span id="Content"></span></body></html>

About this webview call local file, took a bit of time, because the local file will be called when the error, and what what andorid Not allowed to load local resource: file:///android_asset/ is followed by some. Find a half-day problem, found himself is really a layman orz, even the location of asserts folder is misplaced, correct posture should be as follows, if accidentally placed in the Res folder below is not OK (except error or error):

--|build--|src---|assets---|gen---|java---|res

If the location of the folder is not a problem, the code is not a problem, 10,000 suspected that their own machine is out of the question, the official document also has a method:

 Public voidLoaddatawithbaseurl (StringBASEURL,String Data,StringMimeType,StringEncodingStringHistoryurl) parameter list BaseURL If it is a network resource, that is, the URL of the network resource, if it is a local resource, this parameter fills in the root directory of this application.Default is' About:blank '.DataA piece of data to WebView load MIMEType the MIMEType of theDataE.G. ' text/html '. If NULL, defaults to ' text/html '.Encoding the encoding of theDataHistoryurl the URL toUse as the history entry. If NULLDefaults to ' About:blank '. IfNon-null, this must is a valid URL.
3. Call each other

WebView can only show how the Web page can not realize the interaction is no use, light to see how not to touch. And according to the requirements of the project, you need to call JavaScript functions in Java to the local image file into JS inside, so as to preview out, and then on the network of various searches.

3.1 Java Call JavaScript3.1.1 call JavaScript no parameter function

See the. html file loaded into WebView, which defines a parameterless JS function updatehtml (), a function that we need to call manually in the Java code, one line of code is enough

mWebView.loadUrl("javascript:updateHtml()");

Only need to give a button and a listener, click and execute the above statement will be able to invoke JS inside the function.

3.1.2 Calling JavaScript with parameter function

But for the parameters of the JS function is different. We will make a small change to the above demo.html file, let the updatahtml () function become a parameter, the code is as follows:

<html><head>    <script type="Text/javascript">  function updatehtml(num){ document.getElementById ("Content"). InnerHTML = "You have an invoke JavaScript method," + "The num is" + num;}</script></head><body>This is my HTML<span id="Content"></span></body></html>

More interesting is that the call JS with the parameter function of the process a little bit, unexpectedly is directly the parameters prepared, and the function of the name of a whole string, and then to WebView, at that time to see the scare (forgive my ignorance Orz, the village has not seen the world). The Java calling code above is as follows:

mWebView.loadUrl("javascript:updateHtml("3")");
3.2 Java call JavaScript

JavaScript, in turn, calls Java functions a bit more cumbersome, and needs to call WebView's addjavascriptinterface () method to create a calling interface between JS and Java. This function has two parameters:

    1. Object the Java object to inject into this WebView ' s JavaScript context. Null values are ignored.
    2. Name the name used to expose the object in JavaScript

First define an interface between Java and javascript:

package  com.ldx.microtravelnotes.ui.activity; import  android.content.Context; import  android.webkit.JavascriptInterface; import  android.widget.Toast; /** * User:xiaoxiaoda * date:15-7-29 * EMAIL: [email protected] * Project:microtravelno TES */ public  class   webviewinterface  { Context mcontext;  Webviewinterface (Context context) {Mcontext = context; }  @JavascriptInterface  public  void  showtoast  (String msg) {Toast.maketext (Mcontext, MSG,  Toast.length_long). Show (); }}

The method inside this public interface needs to be annotated with @javascriptinterface if it needs to be called by JavaScript, as it may contain potentially threatening code in HTML and JavaScript. So Android 4.1,api 17, which is Jelly_bean, only the public method identified by the Javascriptinterface annotation can be accessed by the JS code.

Then modify the following code inside the demo.html, let the inside of the Click event invoke the public interface code defined above:

<html><head>    <script type="Text/javascript">  function updatehtml(num){ document.getElementById ("Content"). InnerHTML = "You have an invoke JavaScript method," + "The num is" + num;}  function startfunction(msg) { android.showtoast (msg);}</script></head><body>This is my HTML<a onClick="startfunction (' JS invoke Java Success ')" href="" ; >Invoke Java</a><span id="Content"></span></body></html>

You can see that clicking triggers the startfunction () method, which in turn calls the Android.showtoast (msg) method, in which Android in the following statement is a custom name in Java code. It is not fixed that it will be mentioned later. The Showtoast method is the method in the public interface that we define.

The code that needs to be changed in Java is as simple as this:

mWebView.addJavascriptInterface(new WebViewInterface(this"Android");

The Android here is the name of the public interface that you can customize as mentioned above. Follow the above steps to complete the JavaScript call Java functionality.

4. Tips for using

Java inside the WebView is still very powerful, after all, it is so convenient to use, but in dealing with a lot of pictures and animation of the page is still some lag, What to do 0.0, after all, can not be stuck down ah, everywhere asked the big God, seemingly did not find a good solution, but learned some can help a little busy small tricks.

4.1 Start a new process

To WebView's activity to start a new process, webview do not get it off, you should not want to webview your app at any time to get rid of it, to start a new process, and then said to it: "To collapse yourself, do not pull me orz." Starting the method is very simple, in the androidmanifest.xml file found in the activity, add the following code on it:

android:process="packagename.web"
4.2 Add WebView as dynamic as possible

Try not to add a WebView control directly inside the. xml file, the dynamic add in is better, because in the process of destroying activity, you can do some webview in advance, such as timely cleanup of WebView occupied memory ( WebView memory leaks seem a bit serious, I also listen to the Great Gods Orz), also need to pay attention to the creation of WebView need to use the context of applicationcontext instead of activity. The webview should be dealt with in the activity or fragment ondestory () method:

mWebView.stopLoading();mWebView.removeAllViews();mWebView.destroy();mWebView = null;

After invoking the activity's finish () method, the above four lines of code are executed, but even if the activity is destroyed and the process is in progress, a further manual destruction process is required for the webview processing to complete. Then add the following two lines of code,killbackgroundprocesses () The parameter is created when the name of the process, because the current activity belongs to this process, the direct getpackagename () can be obtained, You don't need to add the . Webto the back.

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);activityManager.killBackgroundProcesses(getPackageName());

There are also some more high-end optimization and use techniques temporarily unused, links are also presented, Android WebView development issues and optimization summary.

The above is the individual in the use of webview when some of the views, smoke a little time to summarize, and later also convenient to see their own. Continue to silently catch the project to the Orz ...

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

WebView Usage Summary

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.