WebView usage summary and webview Summary

Source: Internet
Author: User
Tags custom name

WebView usage summary and webview Summary
WebView Summary (ignore directly

I haven't written anything on my blog for a long time. I have summarized my recent learning situation. It is also a course design, a project, and it is almost XX. Recently, another pot was created to create a social travel application. The content of the Travel Notes was edited by the user and uploaded to the server. Different templates were written at the front end and then the images were placed in the template, the previous section is still very slide, and the written templates are pretty nice (it is very good to hit the chicken wet, Android needs to use WebView to browse the travel notes that have been processed. The first time I came into contact with WebView, I felt so excited and mysterious. Next I will show you some experience in using WebView to orz. I haven't been writing anything for a long time. When I come up, I will talk a lot of nonsense (

1. Introduction

In international practice, Let's first look at google's promotion of its own things.

Public class WebView extends AbsoluteLayout implements ViewTreeObserver. onGlobalFocusChangeListener ViewGroup. onHierarchyChangeListenerjava. lang. object upload android. view. view every android. view. viewGroup uses android. widget. absoluteLayout extends android. webkit. webView A View that displays web pages. this class is the basis upon which you can roll your own web browser or simply display some online content within y Our Activity. it uses the WebKit rendering engine to display web pages and between des methods to navigate forward and backward through a history, zoom in and out, perform text searches and more. note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file: <uses-permission android: name = "android. permiss Ion. INTERNET "/> attach my slag translation orz: WebView is a control used to display web pages, this class can be used as the basis for making your own browser or simply displaying some network content in the activity, it uses the WebKit rendering engine to display webpages and display previous pages and next pages in history, scale down and query texts on webpages. It should be noted that in order to allow WebView to access the network, it should be in AndroidManifest. add the following permissions to the xml file (the row above )..... if you access the local html directly, you do not need to add it. But it is better to add it to the local environment to make the game over.

To put it bluntly, it is used to display web pages. In the past, little da only knew what could access the network, but also could access local html files, which will be presented one by one later.

2. Simple use

After learning about it, let's take a look at it.

2.1 load from Network

At the very beginning, I wrote this on the official document.

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

I was shocked when I saw it. I was wondering if it would be so bad. Can I access the website by inputting a url? Then I tried to 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">    <WebView        android:id="@+id/webview"        android:layout_width="match_parent"        android:layout_height="match_parent"/></RelativeLayout>

Turn around and set WebView in the Activity. You must note that mWebView is used directly. setXXX () cannot be found or set. There is a WebSetting in WebView, which is equivalent to a class used to configure the current WebView. It can be used to set whether JavaScript and other content are supported, explore other things by yourself .....

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

Then I found out that this is really a drawback (no picture of your bb ),:

The key point is the loadUrl function. In the above example, the url of baidu is passed to the webview for loading. You can directly browse the homepage of baidu, but you cannot click it like a browser, which requires further processing.There is no pitfall in loading content from the network. Remember to add the application permission and configure WebSetting.

2.2 load from local

After getting in touch with the initial use of WebView, xiaoda quickly reached the front-end, and successfully showed the effect of the front-end. In the previous figure, various great gods asked for the light spray Orz:

However, some templates (consisting of html, css, and js) need to be downloaded from the server to the local server and then previewed. This involves WebView loading local files, and encountered some pitfalls in the implementation process. I 'd like to share it with you. The layout file remains unchanged like the preceding. xml file. The only thing that needs to be changed is the url that is sent to the WebView and changed to get the local file.

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

Demo.html is justAssertsThe content of the html file under the Resource folder is as follows:

It took some time for this WebView to call a local file because an error was reported when calling the local file,andorid Not allowed to load local resource: file:///android_asset/What, what, and what are followed by some. After searching for a problem for half a day, I found that I was a real layman orz, and even put the wrong location in the asserts folder. The correct posture should be as follows, if you do not care about the res folder, it will not work (except for the error or error ):

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

If there is no problem with the folder location and the code is okay, 10 thousand people suspect that something is wrong with their machines. There is another method in the official document:

Public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl) parameter list if the baseUrl is a network resource, that is, the url of the network resource, if it is a local resource, enter the root directory of the application. the default value is 'about: blank '. the mimeType of the data, e.g. 'text/html '. if null, defaults to 'text/html '. encoding the encoding of the datahistoryUrl the URL to use as the history entry. if null defaults to 'about: blank '. if non-null, this must be a valid URL.
3. Mutual calls

WebView only shows how a webpage can be accessed. It is useless to achieve interaction. In addition, according to the project requirements, you need to use java to call the javascript function to put the local image file into js, so that you can preview it, and then search for it on the network.

3.1 Java call JavaScript3.1.1 call JavaScript no-argument function

See the example in the. html file of webview. a js function without parameters is defined.UpdateHtml ()This function needs to be manually called in Java code. A line of code is enough.

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

You only need to add a listener to a button, and then execute the preceding statement to call the functions in js.

3.1.2 call a JavaScript function with Parameters

However, js functions with parameters are different. We will make small modifications to the latest demo.html file to makeUpdataHtml ()The function has a parameter. The Code is as follows:

It is interesting to note that the process of passing parameters in the js function with parameters is a little amazing. Instead, the parameter is directly prepared to form an entire string with the function name and then be sent to WebView together, at that time, I was scared (forgive me for my ignorance, orz, who came from the countryside and never met the world ). The above Java call code is as follows:

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

In turn, JavaScript calls Java functions, which is a little more troublesome.AddJavascriptInterface ()Method To create a call interface between js and java. This function has two parameters:

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: daque@hustunique.com * PROJECT: MicroTravelNotes */public class WebViewInterface {  Context mContext;  WebViewInterface(Context context) {    mContext = context;  }  @JavascriptInterface  public void showToast(String msg) {    Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();  }}

If the methods in this public interface need to be called by JavaScript, the @ JavascriptInterface must be annotated, because the HTML and JavaScript may contain threatening code. Therefore, for Android 4.1, API 17, or JELLY_BEAN, only public methods marked by JavascriptInterface annotations can be accessed by JS Code.

Modify the code in demo.html to call the above-defined public interface code for click events:

It can be seen that the click will triggerStartFunction ()And then call the Android. showToast (msg) method.AndroidIt is a custom name in Java code. It will be mentioned later and is not fixed. The showToast method is the method in the public interface we define.

The code to be modified in Java is as follows, which is also very simple:

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

HereAndroidIs the name of the public interface that can be customized as mentioned above. Follow the steps above to complete the JavaScript call Java function.

4. Tips

The WebView in Java is still very powerful. After all, it is so convenient to use, but it still gets stuck in processing webpages with many images and animations. What should we do? 0.0, after all, you can't get stuck all the time. If you look around, you don't seem to have found a good solution. Instead, you have learned some tips that can help you do a little bit.

4.1 start a new process

Start a new process for the Activity in which the WebView is located, and the WebView will crash if it is difficult. You should not want the WebView to crash your App at any time and start a new process for it, then he said to it, "you have to collapse yourself. Don't pull me orz." The startup method is very simple.AndroidManifest. xmlFind the Activity in the file and add the above Code:

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

Try not. directly Add a WebView control to the xml file. It is better to Add the control dynamically because WebView can be processed in advance during Activity destruction, for example, clean up the memory occupied by WebView in a timely manner (the WebView Memory leakage seems to be a little serious, so I also heard orz from the experts ), in addition, you must use applicationContext instead of activity context to create a webview. In the Activity or FragmentOnDestory ()The WebView method should be processed as follows:

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

After calling the finish () method of the activity, execute the above four lines of code to complete WebView processing. However, even if the activity is destroyed, its process still exists, further manual destruction is required. Then add the following two lines of code to the end,KillBackgroundProcesses ()The parameter in is the name of the Process during creation. Because the current activity belongs to this process, you can get it directly by getPackageName () without adding. Web.

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

There are also some more advanced optimizations and usage tips that are not used for the moment, and links are also presented. Android WebView development problems and optimization summary.

The above are some of my views when using WebView. I will take some time to summarize them and make it easier for me to look at them later. Continue to catch up with the project ..........

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.