Android webview Parsing

Source: Internet
Author: User
Tags http authentication blank page

Original article: webview Parsing
Http://www.eoeandroid.com/thread-233941-1-1.html

----------------------------------------------

Phonegap + jquerymobile early adopters
Http://www.eoeandroid.com/thread-234288-1-1.html

 

A high-performance WebKit kernel browser is built in the Android mobile phone. The SDK is encapsulated as a webview component.
The webview class is the Java-layer View class of the WebKit module. (ALL Android applications that require web browsingProgramYou must create the view object to display and process the requested network resources. Currently, the WebKit module supports HTTP, https, FTP, and JavaScript requests.

As the UI interface of the application, webview provides users with a series of web browsing and user interaction interfaces. Through these interfaces, the customer program accesses the core of WebKit.Code. )

What is WebKit
WebKit is a software framework included in Mac OS X v10.3 and later versions (for v10.2.7 and later versions, it can also be obtained through software updates,
WebKit is also the basis of Mac OS X's Safari web browser. WebKit is an open-source project. It is mainly modified by KDE's khtml and contains some components from Apple.
Traditionally, WebKit contains a web engine WebCore and a script engine javascriptcore, which correspond to KDE's khtml and KJS respectively.
However, as Javascript Engines become more and more independent, WebKit and WebCore are now basically mixed (for example, Google Chrome and Maxthon 3 adopt V8 engines, but they still claim to be WebKit kernels ).
Here we will first try to use webview to browse Web pages on Android,
The SDK Dev Guide provides a simple example of webview. Pay attention to the following points during development: 1. In androidmanifest. XML, the license "android. Permission. Internet" must be used; otherwise, the web page not available error may occur.

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 in the current browser, instead of making a response in the browser of the new Android system, you must overwrite the webviewclient object of webview.

Mwebview. setwebviewclient (NewWebviewclient (){Public BooleanShouldoverrideurlloading (webview view, string URL) {view. loadurl (URL );Return True;}}); Mwebview. setwebviewclient (NewWebviewclient (){Public BooleanShouldoverrideurlloading (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 () and end itself,
If you want to roll back the web page instead of launching a browser, you need to process and consume the back event in the current activity.

Public Boolean onkeydown (INT keycode, keyevent event ){
If (keycode = keyevent. keycode_back) & mwebview. cangoback () {mwebview. Goback (); Return true;} return Super. onkeydown (keycode, event );}

========================================================== ========================================
Put a beautiful page on Tomcat

1. Load the webpage (add permissions)
Define a URL input text box, click the button to open this page with webview
2. compile the data string, webview. loaddata (data, "text/html", "UTF-8 ");
3. Use the setiem of dialog to open the website, move forward, backward, zoom in, zoom out, and clear the history.
4. Use HTML to define the development interface. File:/android_asset/a.html

<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 (use Chom ..)

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 = "OK" onclick = "openconfirm ()">

-----------------------------------------------------
Method in JS debugging in Java:
// Call the JavaScript method in Java through loadurl (). Use the method to be called as the string parameter of the loadurl method.

 
Settings. setjavascriptenabled (True);//Set js to be available in webviewWebview. loadurl ("javascript: myprompt1 ()");

Methods in Java debugging in javascript: (special emphasis on using the android2.2 simulator)

------------- In Java :------

 
Webview. addjavascriptinterface (NewMyinterface (), "myobj ");//Step 2 --- register the object name called in JS myobjWebview. loadurl ("File: // android_asset/test.html"); // Step 1: Define the method to be called in JS
Class myinterface {
Public String getname (){
Return "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ";
}
}

------------ In javascript :-----

 
Function myinterface () {document. getelementbyid ("Myname"). innerhtml =Window. myobj. getname ();}

------------------------------------------------------------------
The webview control has powerful functions. In addition to attributes and settings of general views, it can also perform powerful processing on URL requests, page loading, rendering, and page interaction.
Webview has several customizable points:
(1) set the webchromeclient subclass. webchromeclient will be called when some browser UI interaction actions are affected, for example, webview close and hide, page loading progress, JS confirmation box and warning box, JS loading before, JS operation timeout, webview getting focus, etc. For details, see webchromeclient.

(2) set the webviewclient subclass. The webviewclient will be called when some actions that affect the contents occur, for example, you need to resubmit the form for error submission, load and complete the page, load the resource, process the received HTTP authentication, respond to the page keyboard, and open the URL on the page. For details, see webviewclient.

(3) set the websettings class, which contains multiple configurations. Websettings is used to configure and manage webview configurations, for example, whether file operations can be performed, cache settings, whether pages can be zoomed in or out, whether database APIs, font and text encoding settings are allowed, whether JavaScript scripts are allowed to run, and whether images are automatically allowed loading, whether to allow data and password storage, etc, for details, see websettings.

(4) set the addjavascriptinterface method to bind Java objects to webview, so as to conveniently control Java objects from page JS and interact with HTML pages using local Java code, page automation is even possible. However, this method has security risks. Therefore, if you set this method, make sure that the webview code is completed by yourself. For details, use addjavascriptinterface for automation. See article 5. Use addjavascriptinterface to complete interaction with Js.

1. The back key controls the back of the webpage
By default, the back key of the activity ends the current activity. After webview views many webpages, it is expected to press the back key to return to the previous page. At this time, we need to overwrite the onkeydown function, tell him how to handle it, as shown below:

PublicBooleanOnkeydown (IntKeycode, keyevent event ){If(Webview. cangoback () & event. getkeycode () = keyevent. keycode_back & event. getrepeatcount () = 0) {Webview. Goback ();ReturnTrue;}ReturnSuper. Onkeydown (keycode, event );}

Among them, webview. cangoback () returns true if webview contains a loose browsing record.
Webview. Goback (); indicates that the last access page of webview is returned.
Webview can load and display webpages as a browser.

Network content:
1. loadurl directly displays the webpage content (displays the network image separately)

2. loaddata displays Chinese webpage content (including space processing)

Files in the APK package:
1. loadurl: display HTML and image files in APK

2. loaddata (loaddatawithbaseurl) displays the HTML content Res/layout/Main. xml mixed with images and text in the APK.
----------------------------------------------------------
When the running prompt is web page not available, add the permission to the list file.
<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. If the URL is invalid, a toast message box is displayed to remind the user to enter the correct URL.

----------------------------------------------------------
Steps:
1. Declare webview in the layout File
2. instantiate webview in Activity
3. Call the webview loadurl () method to set the web page to be displayed in wevview.
4. To enable webview to respond to the hyperlink function, call the setwebviewclient () method to set the webview
5. After reading many pages through the webview link, in order to allow webview to support the rollback function, we need to overwrite the onkeydown () method of the activity class. If no processing is performed, click the system rollback key, the entire browser calls finish () instead of rolling back to the previous page.
6. You must add permissions to the androidmanifest. xml file. Otherwise, the web page not available error occurs.

<Uses-Permission Android: Name = "android. Permission. Internet"/>
The following is an example:

Mainactivity. Java

View code

 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; @ override  Public   Void  Oncreate (bundle savedinstancestate ){  Super  . Oncreate (savedinstancestate); setcontentview (R. layout. Main); webview = (Webview) findviewbyid (R. Id. webview );  // Set webview attributes to execute JavaScript scripts Webview. getsettings (). setjavascriptenabled ( True  );  //  Load the webpage to be displayed Webview. loadurl ("http://www.8way.com /" );  //  Set Web View Webview. setwebviewclient ( New  Hellowebviewclient () ;}@ override  //  Set rollback  // Override the onkeydown (INT keycoder, keyevent event) method of 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

View code

<? 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 to 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"> <uses-SDK Android: minsdkversion = "10"/> <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, create a webview in the manifest. Main file,
Then define the webview in the activity and perform the following operations.
1. add permissions: The permission "android. Permission. Internet" must be used in androidmanifest. xml. Otherwise, the web page not available error may occur.
2. Generate a webview component in the activity: webview = new webview (this );
3. Set Basic webview information:
If the accessed page contains JavaScript, webview must be set to support JavaScript.
Webview. getsettings (). setjavascriptenabled (true );
The Touch focus function is requestfocus (); cancel the scroll bar this. setscrollbarstyle (scrollbars_outside_overlay );
4. If you want to click the link for processing by yourself, instead of the link in the browser of the new Android system.
Add an event listening object (webviewclient) to webview and override some of the methods:
Shouldoverrideurlloading: Response to the hyperlink button on the webpage. When you press a connection, webviewclient will call this method,
And pass the parameter: the following URL onloadresource onpagestart onpagefinish onreceiveerror onreceivedhttpauthrequest

5. If JavaScript exists in the accessed page, webview must be set to support JavaScript; otherwise, a blank page is displayed.
Java code webview. getsettings (). setjavascriptenabled (true );

6. If you want to click a link on the page to continue responding in the current browser, instead of making a response in the browser of the new Android system, you must overwrite the webviewclient object of webview: Java code 1. mwebview. setwebviewclient (New webviewclient () {2. 3. 4. 5. 6 .});
The above method tells the system to process the intent by webviewclient, And I will load the URL. The intent that clicks a link is bubbling up,
The shouldoverrideurlloading method return true indicates that after loading, the intent will be consumed and will not bubble up.

7. If you do not do any processing, click the system "back" key when displaying your Brower UI. The entire browser will be "back "}
Public Boolean shouldoverrideurlloading (webview view, string URL) {view. loadurl (URL); Return true;
To other activities, rather than back in the browser's history page.

 

Related Article

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.