First, WebView components introduction
1. What is WebView
1.WebView is a browser component that, in the Android 4.3 system and below, uses the WebKit rendering engine internally and, starting with Android 4.4, uses the chromium rendering engine to render the contents of the view.
The 2.Google encapsulates the WebKit and provides a rich Java interface, the most important of which is the Android.webkit.WebView control.
3.WebKit is an open-source browser engine
2. What can webview do?
1.WebView can load display Web pages, images, etc., can be viewed as a browser
2. Use HTML design software interface layout, put in assets folder, create UI with HTML
3. Permissions
<uses-permission android:name= "Android.permission.INTERNET"/>
Two ways to load Web pages webview
1, loadurl (String URL)
Loadurl ("http://www.163.com") Loadurl ("file:///sdcard/test.html") Loadurl ("File:///sdcard/test1.jpg")
Loadurl ("file:///android_asset/test.htm");
Loadurl ("http://192.168.1.109:2080/webview/abc.html");
Loadurl ("javascript:show (' + JSON + ')"), 2, LoadData (String data,string mimetype,string encoding)/ Loaddatawithbaseurl (String baseUrl, String data, String MimeType, String encoding, string historyurl);
data:html Code
Mimetype:mime type text/html;
Encoding of the encoding:html code Charset=utf-8
3. Describe the two ways of WebView loading Web pages?
1. One way to load URLs, including URLs, SD cards, files in the assets directory, and invoking JS
2. Another way is to load the HTML code, you can specify the MIME type, encoding, etc.
Third, webview other common methods
1, forward, to determine whether the former can be further
GoForward ()
CanGoForward ()
2, a step back to determine whether you can back one step
GoBack () CanGoBack ()
3. Determine if you can forward or backward the specified number of times (negative numbers indicate a fallback n times, positive numbers mean forward n times) gobackorforward (int steps)
Cangobackorforward (steps)
Iv. Auxiliary class of WebView
1, WebSettings class overview:
Both WebSettings and WebView exist in the same life cycle, and when WebView is destroyed, illegalstateexception exceptions are thrown if websettings is used again
This class is primarily responsible for the state configuration management of WebView. When a webview is created for the first time, it is accompanied by a default setting, which is the default setting that WebSettings invokes all getter methods at once. Can get a WebSettings object through Webview.getsettings, this object will be bound with the life cycle of WebView, if the object binding WebView destroyed, and then go to WebSettings method, will be out of the exception illegalstatee Xception.
Set Support JS
Setting.setjavascriptenabled (TRUE);
When you open a page, the adaptive screen
Setting.setusewideviewport (TRUE);
Sets whether the view loads a Web page in overview mode
Setting.setloadwithoverviewmode (TRUE);
Set Display Zoom button
Setting.setbuiltinzoomcontrols (TRUE);
Make the page support zooming
Setting.setsupportzoom (TRUE);
Do not use cache
Setting.setcachemode (Websettings.load_no_cache);
2, Webviewclient
1. Mainly help WebView to handle various notifications, request events
2.shouldOverrideUrlLoading
Example: Pop-up System Browser Workaround example: The override shouldoverrideurlloading method is called when the link is clicked, and returns false to use the current WebView load link, which returns true if the code in the method determines how to display it.
3.onPageStarted
Example: Can do interception operation
Example: This event is the start of loading the page call, usually we can set a loading in this page, tell the user program is waiting for the network response (ProgressDialog)
4.onPageFinished
Example: a page loading complete, you can close the loading bar (ProgressDialog)
Through the WebView load Baidu page, through a simple small demo to achieve
First step: Configure the manifest file
<uses-permission android:name= "Android.permission.INTERNET"/>
<!--6.0 Dynamic Licensing Issues--
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
Step two: Prepare a simple layout
<webview
Android:id= "@+id/webview"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content" ></WebView>
Private WebSettings websettings;
Private ProgressDialog PD;
Private final int sdk_permission_request = 11;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Load the Web page, and set some properties
Initwebview ();
For 6.0 phones, get dynamic authorization
GetPermissions ();
}
private void Initwebview () {
WebView = (WebView) Findviewbyid (R.id.webview); Initializing the control
String url = "Http://www.baidu.com"; Initializing Web pages
Webview.setwebviewclient (New Webviewclient () {
@Override//returns false to use the current WebView load link
public boolean shouldoverrideurlloading (WebView view, String URL) {
return false;
}
@Override//page opens with an action that shows a progress bar
public void onpagestarted (WebView view, String URL, Bitmap favicon) {
if (pd==null) {
PD = new ProgressDialog (mainactivity.this); Create a progress bar
}
Pd.setmessage ("Loading in, please later ..."); Prompt information
Pd.show (); Show progress bar
super.onpagestarted (view, URL, favicon);
}
Perform actions @Override//page closes
public void onpagefinished (WebView view, String URL) {
if (pd!=null) {
Pd.cancel ();//progress bar Cancel Display
}
super.onpagefinished (view, URL);
}
});
WebSettings = Webview.getsettings ();
Websettings.setjavascriptenabled (TRUE); Support JS
Websettings.setusewideviewport (TRUE); Adaptive screens can be scaled at any scale
Websettings.setloadwithoverviewmode (TRUE);//Set whether the page supports overview mode
Websettings.setbuiltinzoomcontrols (TRUE); Set the Zoom button
Websettings.setsupportzoom (TRUE); Make the page support zooming
Websettings.setcachemode (Websettings.load_no_cache); Cache not supported
Webview.loadurl (URL);
}
private void GetPermissions () {
Dynamic authorization is required if the permissions are >=5.0
if (Build.VERSION.SDK_INT >= build.version_codes. M) {
Prepare a Collection
arraylist<string> permissions = new arraylist<> ();
If the permission to read the SD card does not exist, create a save in the collection
if (Checkselfpermission (read_external_storage)! = packagemanager.permission_granted) {
Permissions.add (Read_external_storage);
}
if (Permissions.size () >0) {
Requestpermissions (Permissions.toarray (New String[permissions.size ())), sdk_permission_request);
}else {
Initwebview ();
}
}else {
Initwebview ();
}
}
@Override//6.0 Dynamic Authorization
public void Onrequestpermissionsresult (int requestcode, @NonNull string[] permissions, @NonNull int[] grantresults) {
Super.onrequestpermissionsresult (Requestcode, permissions, grantresults);
Switch (requestcode) {
Case Sdk_permission_request:
if (grantresults.length>0 && grantresults[0] = = packagemanager.permission_granted) {
Allow
Toast.maketext (This, "authorized", Toast.length_short). Show ();
}else {
Not allowed
Toast.maketext (This, "Deny authorization", Toast.length_short). Show ();
}
Break
}
}
@Override//When the return key is clicked and can be returned
public boolean onKeyDown (int keycode, keyevent event) {
if (Keycode==keyevent.keycode_back && webview.cangoback ()) {//If the return key is clicked and WebView is able to return
Webview.goback ();
return true;
}
If it can return and can return two steps at once
if (keycode = = Keyevent.keycode_back && webview.cangobackorforward (-2)) {
Webview.gobackorforward (-2);
return true;
// }
Return Super.onkeydown (KeyCode, event);
}
Webchromeclient
1. Discussing the role of webchromeclient
The main auxiliary webview Processing JavaScript dialog box, website icon, website title, loading progress, close webview, etc., common rewriting methods are: Onjsalert, onjsconfirm, Onjsprompt, Onreceivedicon, Onreceivedtitle, onprogresschanged, Onclosewindow
2.onJsAlert parameter has only one, display warning box information; no return value
Only one of the 3.onJsConfirm parameters. Displays the information for the prompt box. Press OK to return true; Press Cancel to return false.
The 4.onJsPrompt on parameter has two, the first parameter, which displays the information of the prompt input box. The second parameter, which displays the default value of the input box. Returns the value entered by the user.
5.onReceivedIcon Note You must first open the icon database, otherwise you cannot get to the page icon
6.onReceivedTitle get the title of the page as the title of the application to display
7.onProgressChanged get the Web page loading progress, displayed in the TextView control (think how to display in the progress bar)
8.onCloseWindow Close Web page (WebView)
First step: Configure the manifest file
<uses-permission android:name= "Android.permission.INTERNET"/>
Step Two: Layout file
Activity_main.xml file
<webview
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
Android:id= "@+id/webview" ></WebView>
Promptdialog.xml file
<textview
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
Android:id= "@+id/tv"/>
<edittext
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
Android:id= "@+id/et"/>
<linearlayout
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
android:orientation= "Horizontal" >
<button
Android:id= "@+id/ok"
Android:text= "OK"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:layout_weight= "1"/>
<button
Android:id= "@+id/cancel"
Android:text= "Cancel"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:layout_weight= "1"/>
</LinearLayout>
Step Three: Code implementation
Private WebView WebView;
Private WebSettings websettings;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
WebView = (WebView) Findviewbyid (R.id.webview);
String url = "http://192.168.15.103:8080/webview/alert.html";
String url = "http://192.168.15.103:8080/webview/confrim.html";
String url = "http://192.168.15.103:8080/webview/prompt.html";
Webview.setwebchromeclient (New Webchromeclient () {
@Override
public boolean Onjsalert (WebView view, string URL, string message, jsresult result) {
Alertdialog.builder Builder = new Alertdialog.builder (View.getcontext ());
Builder.settitle ("Alert Alert box")
. Setmessage (Message)
. Setpositivebutton ("OK", NULL)
. Show ();
Result.confirm (); Click OK, the dialog box closes
return true;
}
@Override
public boolean onjsconfirm (WebView view, string URL, String message, final Jsresult result) {
Alertdialog.builder Builder = new Alertdialog.builder (View.getcontext ());
Builder.settitle ("Confirm Confirmation information")
. Setmessage (Message)
. Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {
@Override
public void OnClick (dialoginterface dialoginterface, int i) {
Result.confirm ();
}
})
. Setneutralbutton ("Cancel", new Dialoginterface.onclicklistener () {
@Override
public void OnClick (dialoginterface dialoginterface, int i) {
Result.cancel ();
}
})
. Show ();
return true;
}
@Override
public boolean onjsprompt (WebView view, string URL, String message, String defaultvalue, final Jspromptresult result) {
Final Dialog Dialog = new Dialog (mainactivity.this);
Dialog.setcontentview (R.layout.promptdialog);
Dialog.settitle ("Prompt input information");
TextView TV = (TextView) Findviewbyid (r.id.tv);
Final EditText et = (EditText) Findviewbyid (r.id.et);
Button OK = (button) Dialog.findviewbyid (R.id.ok);
button Cancel = (Button) Dialog.findviewbyid (R.id.cancel);
Tv.settext (message);
Et.settext (defaultvalue);
Ok.setonclicklistener (New View.onclicklistener () {//OK
@Override
public void OnClick (view view) {
Result.confirm (Et.gettext (). toString ());//Pass the value of the Editext in the past
Dialog.cancel ();
}
});
Cancel.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (view view) {
Result.cancel ();
Dialog.cancel ();
}
});
Dialog.setonkeylistener (New Dialoginterface.onkeylistener () {
@Override
public boolean OnKey (dialoginterface dialoginterface, int keycode, keyevent keyevent) {
if (keycode = = Keyevent.keycode_back) {
Result.cancel ();
Dialog.cancel ();
return true;
}
return false;
}
});
Dialog.show ();
return true;
}
});
Webview.setwebviewclient (New Webviewclient () {
@Override
public boolean shouldoverrideurlloading (WebView view, String URL) {
return false;
}
});
Webview.loadurl (URL);
WebSettings = Webview.getsettings ();
Websettings.setjavascriptenabled (TRUE); Support JS
Websettings.setusewideviewport (TRUE); Adaptive screen scaling any scale
Websettings.setusewideviewport (TRUE); Sets whether the view loads an overview mode page for the purpose of a screen to display all the contents of this page
Websettings.setbuiltinzoomcontrols (TRUE); Show Zoom button
Websettings.setsupportzoom (TRUE); Make the page support zooming
Websettings.setcachemode (Websettings.load_no_cache); Do not use the cache can easily modify the software errors in the problem
}
Basic use of WebView