The use resolution of WebView components for Android development _android

Source: Internet
Author: User
Tags event listener http authentication mixed blank page
A high-performance webkit kernel browser is built into the Android phone and is encapsulated in an SDK called the WebView component.
The WebView class is the view class of the WebKit module's Java layer, where all Android applications that need to use the Web browsing feature create the View object to display and process the requested network resources. Currently, the WebKit module supports HTTP, HTTPS, FTP, and JavaScript requests.
WebView, as the UI interface for the application, provides users with a series of web browsing and user interface, through which client programs access the WebKit core code. )

What is WebKit
WebKit is the software framework included with the Mac OS X v10.3 and above (v10.2.7 and above versions are also available through software updates).
WebKit is also the basis of the Safari Web browser for Mac OS X. WebKit is an open source project that is largely modified by KDE khtml and contains some of the components from Apple.
Traditionally, WebKit contains a Web engine WebCore and a script engine javascriptcore, which correspond to KDE khtml and KJS respectively.
However, as the JavaScript engine becomes more independent, WebKit and WebCore are now largely mixed (for example, Google Chrome and Maxthon 3 use the V8 engine, but they still claim to be the WebKit kernel).
Here we have a preliminary experience in Android is using WebView to browse the Web,

The Dev Guide in the SDK has a simple example in WebView. In the development process should note a few: 1.androidmanifest.xml must use the license "Android.permission.INTERNET", otherwise the WEB page not available error.
2. If you have JavaScript on the page you are visiting, WebView must set up to support JavaScript. Webview.getsettings (). Setjavascriptenabled (True);
3. If the link in the page, if you want to click on the link to continue to respond in the current browser, rather than the new Android system browser should be linked, you must overwrite the WebView Webviewclient object.
Mwebview.setwebviewclient (New Webviewclient () {public Boolean shouldoverrideurlloading (webview view, String URL) { View.loadurl (URL); return true; } });
Mwebview.setwebviewclient (New Webviewclient () {public Boolean shouldoverrideurlloading (webview view, String URL) { View.loadurl (URL); return true; } });
4. If you do not do any processing, browsing the Web, click the system "back" key, the entire Browser will call finish () and end itself,
If the page you want to browse is rolled back instead of the browser, you will need to process and consume it in the current activity.
Copy Code code as follows:

public boolean onKeyDown (int keycode, keyevent event) {<BR> if ((keycode = = keyevent.keycode_back) && mwebvi Ew.cangoback ()) {
Mwebview.goback ();
return true;
}
Return Super.onkeydown (KeyCode, event);
}

Put a nice page on Tomcat
1. Load Web page (plus permissions)
Define a URL input text box, click the button to open this page with WebView
2. Write the data string, Webview.loaddata (data, "text/html", "UTF-8");
3. With dialog Setiem Open the Web site, forward, back, zoom in, shrink, clear history.
4. Define the development interface with HTML. File:/android_asset/a.html
Copy Code code as follows:

<script>
function Loadurl () {}
</script>
< select Name= "" >
<option value= ""/>
<option value= ""/>
</select>
Webview.getsettings (). Setjavascriptenabled (True);
Webview.getsettings (). Setbuiltinzoomcontrols (True);
Webview.loadurl (file:///...);

5.js dialog box (with Chom ...)
Copy Code code as follows:

function Openalert () {
Window.alert ("");
}
function Openconfirm () {
if (window.confirm) (Do you want to delete this information?) ")){
Window.location= "myjs.html";//-------------------!!!
}
}
<input type= "Submit" value= "Warning" onclick= "Openalert ()" >
< input type= "submit" value= "confirmation" onclick= "openconfirm ()" >

Java Tuning JS Method:
Copy Code code as follows:

Invoking JavaScript methods in Java is done through Loadurl (), using the method to be invoked as a string argument to the Loadurl method
Settings.setjavascriptenabled (TRUE);/set to WebView available JS
Webview.loadurl ("javascript:myprompt1 ()");

JavaScript in Java methods: (special emphasis to use the Android2.2 version of the simulator)
Copy Code code as follows:

Webview.addjavascriptinterface (New MyInterface (), "myobj")//Second Step---Register the object name called in JS MyObj
Webview.loadurl ("file:///android_asset/test.html");
Step One: Define the method to be called in JS
Class myinterface{
Public String GetName () {
return "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
}
}

------------javascript:-----
Copy Code code as follows:

function MyInterface () {
document.getElementById ("MyName"). InnerHTML = Window.myobj.getname ();
}

WebView control features a powerful, in addition to the general view of the properties and settings, but also the URL request, page load, rendering, page interaction for powerful processing.
WebView has several points that can be customized:
(1) Set the Webchromeclient subclass, Webchromeclient will be invoked in some of the effects of browser UI interaction, such as webview shutdown and hide, page load progress, JS confirmation box and Warning box, JS before loading, JS operation timeout, WebView get focus and so on, see webchromeclient
(2) Set the Webviewclient subclass, Webviewclient will be invoked when some of the actions that affect the content are noisy, such as the wrong submission of the form needs to be resubmitted, the page starts loading and loading complete, the resource is loaded, the HTTP authentication needs processing, the page keyboard responds, The URL on the page to open processing, and so on, see webviewclient
(3) Set the WebSettings class, which contains multiple configurations. WebSettings is used to configure and manage the configuration of the webview, such as whether you can do file operations, cache settings, whether the page supports zooming in and out, whether to allow database APIs, font and text encoding settings, whether to allow JS scripts to run, whether to allow pictures to automatically load, Whether to allow data and password preservation, etc., see websettings
(4) Set the Addjavascriptinterface method, the Java object binding to the WebView, to facilitate the control of Java objects from the page JS, the implementation of local Java code and HTML pages to interact with, or even to automate the page. But this is a security risk, so if you set this method, make sure that the WebView code is done by itself, detailed use of addjavascriptinterface for automation see article 5 use addjavascriptinterface completion and JS interaction
1, Back key control page backward
Activity default back key processing to end the current Activity,webview view a lot of pages, want to press the back key to return to the last browsed page, this time we need to overwrite the onkeydown function, tell him how to deal with, as follows:
Copy Code code as follows:

public boolean onKeyDown (int keycode, keyevent event) {
if (Webview.cangoback () && event.getkeycode () = = Keyevent.keycode_back && event.getrepeatcount () = = 0) {
Webview.goback ();
return true;
}
Return Super.onkeydown (KeyCode, event);
}

where Webview.cangoback () returns True when WebView contains a browsable browse record
Webview.goback (); Represents the last access page that returns WebView
WebView (network view) can load a display page, which can be viewed as a browser.
Network content:
1, Loadurl directly display the content of the Web page (show the network picture alone)
2, LoadData display Chinese Web page content (including the processing of space)
APK in package file:
1, loadurl display apk html and picture files
2. LoadData (loaddatawithbaseurl) displays HTML content mixed with picture and text in apk res/layout/main.xml
----------------------------------------------------------
Add permissions to the manifest file when the run prompt is Web page not available
<uses-permission android:name= "Android.permission.INTERNET"/>
The Urlutil.isnetworkurl (String Uri) method is used to determine whether the URL entered by the user is valid, or if it is invalid, a toast message box is displayed to remind the user to enter the correct URL
----------------------------------------------------------
Steps:
1, in the layout file declared WebView
2, in the activity of the instantiation of WebView
3, call the WebView Loadurl () method, set Wevview to display the page
4, in order to allow WebView to respond to the hyperlink function, call the Setwebviewclient () method, set the WebView view
5, with WebView point links to see a lot of pages later in order to allow WebView support fallback function, need to cover the Activity Class onkeydown () method, if do not do any processing, click System Fallback key, the entire browser will call finish () and end itself, Instead of retreating back to the previous page
6. You need to add permissions to the Androidmanifest.xml file, otherwise the Web page not available error occurs.
<uses-permission android:name= "Android.permission.INTERNET"/>
Here are the specific examples:
Mainactivity.java
Copy Code code as follows:

Package com.android.webview.activity;
Import android.app.Activity;
Import Android.os.Bundle;
Import android.view.KeyEvent;
Import Android.webkit.WebView;
Import android.webkit.WebViewClient;
public class Mainactivity extends activity {
Private WebView WebView;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
WebView = (webview) Findviewbyid (R.id.webview);
Set the WebView property to execute JavaScript script
Webview.getsettings (). Setjavascriptenabled (True);
Load pages that need to be displayed
Webview.loadurl ("http://www.8way.com/");
Set Web View
Webview.setwebviewclient (New Hellowebviewclient ());
}
@Override
Set fallback
onkeydown (int keycoder,keyevent event) method covering the Activity class
public boolean onKeyDown (int keycode, keyevent event) {
if ((keycode = = keyevent.keycode_back) && webview.cangoback ()) {
Webview.goback (); GoBack () indicates that the previous page of WebView is returned
return true;
}
return false;
}
Web View
Private class Hellowebviewclient extends Webviewclient {
@Override
public boolean shouldoverrideurlloading (webview view, String URL) {
View.loadurl (URL);
return true;
}
}
}

Main.xml
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
android:orientation= "Vertical"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
>
<webview
Android:id= "@+id/webview"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
/>
</LinearLayout>
Add permissions in the Androidmanifest.xml file
<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Com.android.webview.activity"
Android:versioncode= "1"
Android:versionname= "1.0" >
&LT;USES-SDK android:minsdkversion= "Ten"/>
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<activity android:name= ". Mainactivity "
Android:label= "@string/app_name" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<uses-permission android:name= "Android.permission.INTERNET"/>
</manifest>

Summary of WebView Learning records:
First you create a webview in the Manifest.main file,
Then define the WebView in the activity and then do the following related operations.
1, add permissions: Androidmanifest.xml must use the license "Android.permission.INTERNET", otherwise the WEB page not available error.
2, in the activity to generate a WebView component: WebView WebView = new WebView (this);
3, set WebView basic information:
If you have JavaScript on the page you are accessing, WebView must set up to support JavaScript.
Webview.getsettings (). Setjavascriptenabled (True);
Touch Focus functions Requestfocus (); Cancel the scroll bar This.setscrollbarstyle (scrollbars_outside_overlay);
4 If you want to click on the link by yourself, instead of opening the new Android system browser should be linked in the ring.
Add an Event Listener object (webviewclient) to WebView and rewrite some of these methods:
Shouldoverrideurlloading: A response to a hyperlink button in a Web page. Webviewclient calls this method when a connection is pressed.
and passing parameters: pressed URL onloadresource onpagestart onpagefinish onreceiveerror onreceivedhttpauthrequest
5. If you have JavaScript on the page you are visiting, WebView must set up JavaScript support, otherwise a blank page will be displayed.
Java Code webview.getsettings (). Setjavascriptenabled (True);
6, if the link in the page, if you want to click on the link to continue in the current browser response, rather than the new Android system browser should be linked to the ring, must overwrite WebView webviewclient object: Java code 1.MWEBVIEW.S Etwebviewclient (New Webviewclient () {2. 3.4. 5.6. });
The above method tells the system by me this webviewclient handles this Intent and I will load the URL. Clicking on a link to the Intent is bubbling up,
The Shouldoverrideurlloading method return true means that after I load the Intent is consumed and no longer bubbles up.
7, if you do not do any processing, in the display of your brower UI, click the System "back" key, the entire Browser as a whole "back"}
public boolean shouldoverrideurlloading (webview view, String URL) {view.loadurl (URL);
To other activity, rather than the hope of back in the Browser history page.

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.