Android WebView loading HTML5 introduction _android

Source: Internet
Author: User
Tags time limit sessionstorage
Multi-resolution problems with Android devices
Android Browser default preview mode Browse will reduce the page WebView will be displayed in the original size
The Android browser and webview default to MDPI. HDPI equivalent to MDPI 1.5 times times ldpi equivalent to 0.75 times times
Three ways to solve: 1 viewport attribute 2 CSS control 3 JS control
1 viewport attributes are placed in the <meta> of HTML
HTML code
Copy Code code as follows:

<spanstyle= "Font-size:x-small" > <title>Exmaple</title>
<metaname= "Viewport" content= "Width=device-width,user-scalable=no"/>

The attributes of viewport in Meta are as follows
HTML code
Copy Code code as follows:

<spanstyle= "Font-size:x-small" > <metaname= "Viewport"
Content= "
Height = [Pixel_value | device-height],
width = [Pixel_value | device-width],
Initial-scale = Float_value,
Minimum-scale = Float_value,
Maximum-scale = Float_value,
user-scalable = [yes | no],
target-densitydpi = [Dpi_value | device-dpi |
high-dpi | medium-dpi | LOW-DPI]
"
/></span>


2 CSS Control device density
Create a separate style sheet for each density (note that the Webkit-device-pixel-ratio 3 values correspond to 3 resolutions)

HTML code
Copy Code code as follows:

<linkrel= "stylesheet" media= "screen and (-webkit-device-pixel-ratio:1.5)" href= "Hdpi.css"/>
<linkrel= "stylesheet" media= "screen and (-webkit-device-pixel-ratio:1.0)" href= "Mdpi.css"/>
<linkrel= "stylesheet" media= "screen and (-webkit-device-pixel-ratio:0.75)" href= "Ldpi.css"/>

In a style sheet, specify a different style

HTML code
Copy Code code as follows:

#header {
<spanstyle= "White-space:pre" > </SPAN> background:url (medium-density-image.png);
}
@media screen and (-webkit-device-pixel-ratio:1.5) {
CSS for high-density screens
#header {
Background:url (high-density-image.png);
}
}
@media screen and (-webkit-device-pixel-ratio:0.75) {
CSS for low-density screens
#header {
Background:url (low-density-image.png);
}
}


HTML code
Copy Code code as follows:

<metaname= "Viewport" content= "target-densitydpi=device-dpi, Width=device-width"/>
[Code]
3 JS Control
The Android browser and WebView support querying the DOM properties of the current set density
Window.devicepixelratio the same value has 3 (0.75,1,1.5 corresponds to 3 resolutions)
The method of querying device density in JS
JS Code
[Code]
if (Window.devicepixelratio = = 1.5) {
Alert ("This are a high-density screen");
} elseif (window.devicepixelration = = 0.75) {
Alert ("This are a low-density screen");
}

building HTML5 applications in Android
Use the WebView control in the same way as other controls use a <WebView> label in layout
WebView does not include navigation bar, address bar and other full browser features, only to display a Web page
Load a Web page in WebView, using Loadurl ()
Java code
Copy Code code as follows:

WebView Mywebview = (webview) Findviewbyid (R.id.webview);
Mywebview.loadurl ("http://www.example.com");

Note to include access to the Internet in the manifest file:
XML code
Copy Code code as follows:

<uses-permissionandroid:name= "Android.permission.INTERNET"/>

Click on a link in Android, the default is to invoke the application to start, so webview need to handle this action via Webviewclient
Java code
Copy Code code as follows:

Set Webviewclient
Webview.setwebviewclient (New Webviewclient () {
Publicboolean shouldoverrideurlloading (webview view, String URL) {
View.loadurl (URL);
Returntrue;
}
Publicvoid onpagefinished (webview view, String URL) {
super.onpagefinished (view, URL);
}
Publicvoid onpagestarted (webview view, String URL, Bitmap favicon) {
super.onpagestarted (view, URL, favicon);
}
});

This Webviewclient object can be extended by itself, such as
Java code
Copy Code code as follows:

Privateclass Mywebviewclient extends Webviewclient {
Publicboolean shouldoverrideurlloading (webview view, String URL) {
if (Uri.parse (URL). GetHost (). Equals ("www.example.com")) {
Returnfalse;
}
Intent Intent = new Intent (Intent.action_view, Uri.parse (URL));
StartActivity (Intent);
Returntrue;
}
}

After:
Java code
Copy Code code as follows:

WebView Mywebview = (webview) Findviewbyid (R.id.webview);
Mywebview.setwebviewclient (New Mywebviewclient ());

In addition to the user's customary considerations need to be more like a browser webview, that is, you need to be able to rewind the history
Therefore, you need to overwrite the system's fallback key Goback,goforward to navigate the history page backwards
Java code
Copy Code code as follows:

Publicboolean onKeyDown (int keycode, keyevent event) {
if ((keycode = = keyevent.keycode_back) && mywebview.cangoback () {
Mywebview.goback ();
Returntrue;
}
Returnsuper.onkeydown (KeyCode, event);
}

Java code
Copy Code code as follows:

WebView Mywebview = (webview) Findviewbyid (R.id.webview);
WebSettings websettings = Mywebview.getsettings ();
Websettings.setjavascriptenabled (TRUE);

(The websetting used here is very useful to open a lot of settings in the subsequent local storage, location, etc. will use)
1 function method of calling Android in JS
First you need to create an interface in your Android program
Java code
Copy Code code as follows:

Finalclass Injavascript {
Publicvoid runonandroidjavascript (Final String str) {
Handler.post (New Runnable () {
Publicvoid Run () {
TextView show = (TextView) Findviewbyid (R.id.textview);
Show.settext (str);
}
});
}
}

Java code
Copy Code code as follows:

Add an instance of this class to the JS Global Object window.
So you can use WINDOWS.INJS to invoke its method
Webview.addjavascriptinterface (New Injavascript (), "Injs");
Calling JS code in JavaScript
function Sendtoandroid () {
var str = "Cookie call to the Android method from JS";
Windows.injs.runOnAndroidJavaScript (str);//Call Android function
}

2 ways to call JS in Android
In the JS method:
JS Code
Copy Code code as follows:

function Getfromandroid (str) {
Document.getelementbyidx_x_x_x ("Android"). Innerhtml=str;
}

Calling this method Java code on Android
Copy Code code as follows:

Button button = (button) Findviewbyid (R.id.button);
Button.setonclicklistener (New Onclicklistener () {
Publicvoid OnClick (View arg0) {
Calling methods in JavaScript
Webview.loadurl ("javascript:getfromandroid (' Cookie call the JS function from Android ')");
}
});

3 Android in the processing of JS warning, dialog boxes, etc. in Android to deal with JS warning, dialog boxes, etc. need to WebView set Webchromeclient object
Java code
Copy Code code as follows:

Set Webchromeclient
Webview.setwebchromeclient (New Webchromeclient () {
Handling Alert in JavaScript
Publicboolean Onjsalert (webview view, string URL, String message, final Jsresult result) {
Build a builder to display the dialog box in the Web page
Builder Builder = new Builder (mainactivity.this);
Builder.settitle ("Alert");
Builder.setmessage (message);
Builder.setpositivebutton (Android. R.string.ok,
New Alertdialog.onclicklistener () {
Publicvoid OnClick (dialoginterface dialog, int which) {
Result.confirm ();
}
});
Builder.setcancelable (FALSE);
Builder.create ();
Builder.show ();
Returntrue;
};
Handling the Confirm in JavaScript
Publicboolean onjsconfirm (webview view, string URL, String message, final Jsresult result) {
Builder Builder = new Builder (mainactivity.this);
Builder.settitle ("confirm");
Builder.setmessage (message);
Builder.setpositivebutton (Android. R.string.ok,
New Alertdialog.onclicklistener () {
Publicvoid OnClick (dialoginterface dialog, int which) {
Result.confirm ();
}
});
Builder.setnegativebutton (Android. R.string.cancel,
New Dialoginterface.onclicklistener () {
Publicvoid OnClick (dialoginterface dialog, int which) {
Result.cancel ();
}
});
Builder.setcancelable (FALSE);
Builder.create ();
Builder.show ();
Returntrue;
};
@Override
Set a progress bar for Web page loading
Publicvoid onprogresschanged (webview view, int newprogress) {
MainActivity.this.getWindow (). Setfeatureint (window.feature_progress, newprogress * 100);
Super.onprogresschanged (view, newprogress);
}
To set the title of the application
Publicvoid Onreceivedtitle (webview view, String title) {
MainActivity.this.setTitle (title);
Super.onreceivedtitle (view, title);
}
});

the debugging in Android
Output log information via JS code
JS Code
JS Code: Console.log ("Hello World");
Log information: Console:hello World http://www.example.com/hello.html:82
Implement the Onconsolemesaage () callback method in webchromeclient to print information in Logcat
Java code
Copy Code code as follows:

WebView Mywebview = (webview) Findviewbyid (R.id.webview);
Mywebview.setwebchromeclient (New Webchromeclient () {
Publicvoid onconsolemessage (String message, int linenumber, string sourceid) {
LOG.D ("MyApplication", Message + "--From line"
+ linenumber + "of"
+ SourceID);
}
});

and Java code
Copy Code code as follows:

WebView Mywebview = (webview) Findviewbyid (R.id.webview);
Mywebview.setwebchromeclient (New Webchromeclient () {
Publicboolean onconsolemessage (consolemessage cm) {
LOG.D ("MyApplication", cm.message () + "--From line"
+ cm.linenumber () + "of"
+ Cm.sourceid ());
Returntrue;
}
});

*consolemessage also includes a messagelevel indicating the type of console delivery information. You can query the information level with Messagelevel () to determine the severity of the information, and then use the appropriate log method or take other appropriate measures.
The application of HTML5 local storage in Android
HTML5 provides 2 new methods of client-side storage data: Localstorage No time limit sessionstorage data storage for a session
JS Code
Copy Code code as follows:

<script type= "Text/javascript" >
Localstorage.lastname= "Smith";
document.write (Localstorage.lastname);
</script>
<script type= "Text/javascript" >
Sessionstorage.lastname= "Smith";
document.write (Sessionstorage.lastname);
</script>

WebStorage API:
JS Code
Copy Code code as follows:

Empty storage
Localstorage.clear ();
Set a key value
Localstorage.setitem ("Yarin", "Yangfegnsheng");
Gets a key value
Localstorage.getitem ("Yarin");
Gets the name of the key that specifies the subscript (as Array)
Localstorage.key (0);
Return "fresh"//delete a key value
Localstorage.removeitem ("Yarin");
Be sure to turn it on in the settings.
Setdomstorageenabled (True)
Operating Java code in Android
Enable database
Websettings.setdatabaseenabled (TRUE);
String dir = This.getapplicationcontext (). Getdir ("Database", Context.mode_private). GetPath ();
Setting the database path
Websettings.setdatabasepath (dir);
You must open the using Localstorage
Websettings.setdomstorageenabled (TRUE);
Expand the capacity of the database (implemented in webchromeclinet)
Publicvoid onexceededdatabasequota (string url, String databaseidentifier, long Currentquota,
Long estimatedsize, long Totalusedquota, Webstorage.quotaupdater quotaupdater) {
Quotaupdater.updatequota (EstimatedSize * 2);
}
In JS, according to the general database Operation JS Code
function Initdatabase () {
try {
if (!window.opendatabase) {
Alert (' Databases are not supported by your browser ');
} else {
var shortname = ' yarindb ';
var version = ' 1.0 ';
var displayName = ' Yarin db ';
var maxSize = 100000; In bytes
Yarindb = OpenDatabase (shortname, version, DisplayName, maxSize);
Createtables ();
SelectAll ();
}
catch (e) {
if (E = = 2) {
Version mismatch.
Console.log ("Invalid database version.");
} else {
Console.log ("Unknown error" + E + ".");
}
Return
}
}
function Createtables () {
Yarindb.transaction (
function (transaction) {
Transaction.executesql (' CREATE TABLE IF not EXISTS Yarin (id INTEGER not NULL PRIMARY KEY, Name text not Null,desc TEXT not NULL); ', [], Nulldatahandler, ErrorHandler;
}
);
InsertData ();
}
function InsertData () {
Yarindb.transaction (
function (transaction) {
Starter data when page is initialized
var data = [' 1 ', ' Yarin yang ', ' I am Yarin '];
Transaction.executesql ("INSERT into Yarin (ID, name, desc) VALUES (?,?,?)", [data[0], data[1], data[2]);
}
);
}
function ErrorHandler (transaction, error) {
if (error.code==1) {
DB Table already exists
} else {
Error is a human-readable string.
Console.log (' Oops. Error was ' +error.message+ ' (Code ' +error.code+ ') ');
}
Returnfalse;
}

function Nulldatahandler () {
Console.log ("SQL Query succeeded");
}
function SelectAll () {
Yarindb.transaction (
function (transaction) {
Transaction.executesql ("select * from Yarin;", [], Dataselecthandler, ErrorHandler);
}
);
}
function Dataselecthandler (transaction, results) {
Handle the results
for (var i=0; i<results.rows.length; i++) {
var row = Results.rows.item (i);
var newfeature = new Object ();
Newfeature.name = row[' name '];
Newfeature.decs = row[' desc '];
Document.getelementbyidx_x_x_x ("name"). Innerhtml= "Name:" +newfeature.name;
document.getelementbyidx_x_x_x ("desc"). Innerhtml= "desc:" +NEWFEATURE.DECS;
}
}
function UpdateData () {
Yarindb.transaction (
function (transaction) {
var data = [' Fengsheng yang ', ' I am Fengsheng '];
Transaction.executesql ("UPDATE yarin SET name=?, desc=?") WHERE id = 1 ", [data[0], data[1]]);
}
);
SelectAll ();
}
function Ddeletetables () {
Yarindb.transaction (
function (transaction) {
Transaction.executesql ("DROP TABLE Yarin;", [], Nulldatahandler, ErrorHandler);
}
);
Console.log ("Table ' page_settings ' has been dropped.");
}

Notice the initialization work in onload
Copy Code code as follows:

function Initlocalstorage () {
if (window.localstorage) {
Textarea.addeventlistener ("KeyUp", function () {
window.localstorage["value"] = This.value;
window.localstorage["Time" = new Date (). GetTime ();
}, False);
} else {
Alert ("Localstorage are not supported in this browser.");
}
}
Window.onload = function () {
Initdatabase ();
Initlocalstorage ();
}

The application of HTML5 location service in Android
Java code in Android
Copy Code code as follows:

Enable geo-positioning
Websettings.setgeolocationenabled (TRUE);
Set the location of the database path
Websettings.setgeolocationdatabasepath (dir);
Configure permissions (also implemented in webchromeclient)
Publicvoid ongeolocationpermissionsshowprompt (String origin,
Geolocationpermissions.callback Callback) {
Callback.invoke (origin, True, false);
Super.ongeolocationpermissionsshowprompt (origin, callback);
}
Add permission XML code to manifest
<uses-permissionandroid:name= "Android.permission.ACCESS_FINE_LOCATION"/>
<uses-permissionandroid:name= "Android.permission.ACCESS_COARSE_LOCATION"/>
HTML5 in the Navigator.geolocation object to obtain geographical location information commonly used Navigator.geolocation objects have the following three ways: JS code
Get Current Location
Navigator.geolocation.getCurrentPosition (Success_callback_function, error_callback_function, position_options)
Continued access to geographic location
Navigator.geolocation.watchPosition (Success_callback_function, error_callback_function, position_options)
Clear persistent access to geographic events
Navigator.geolocation.clearWatch (watch_position_id)
Where Success_callback_function is successfully processed after the function, Error_callback_function returned after the failure of the processing function, parameter position_options is the configuration item in JS code JS code
Positioning
function Get_location () {
if (navigator.geolocation) {
Navigator.geolocation.getCurrentPosition (show_map,handle_error,{enablehighaccuracy:false,maximumage:1000, timeout:15000});
} else {
Alert ("Your browser does not support HTML5 geolocation");
}
}
function Show_map (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var city = position.coords.city;
telnet localhost 5554
Geo fix-82.411629 28.054553
Geo fix-121.45356 46.51119 4392
Geo Nmea $GPGGA, 001431.092,0118.2653,n,10351.1359,e,0,00,,-19.6,m,4.1,m,,0000*5b
Document.getelementbyidx_x_x_x ("Latitude"). Innerhtml= "Latitude:" +latitude;
Document.getelementbyidx_x_x_x ("Longitude"). Innerhtml= "Longitude:" +longitude;
Document.getelementbyidx_x_x_x ("City"), innerhtml= "City:" +city;
}
function Handle_error (err) {
Switch (err.code) {
Case 1:
Alert ("Permission denied");
Break
Case 2:
Alert ("The network is down or the position satellites can ' t be contacted");
Break
Case 3:
Alert ("Time Out");
Break
Default
Alert ("Unknown error");
Break
}
}

Where the Position object contains many data error codes and options to view the document
Constructing HTML5 Off-line application
Need to provide a cache manifest file for all resources that need to be used offline
such as manifest code
CACHE MANIFEST
#这是注释
Images/sound-icon.png
Images/background.png
Clock.html
Clock.css
Clock.js
Network:
test.cgi
CACHE:
Style/default.css
Fallback:
/files/projects/projects
Declaring JS Code
Copy Code code as follows:

if (Window.applicationCache.status = = Window.applicationCache.UPDATEREADY)  {
Window.applicationCache.update (); 
}
Online Status detection HTML5 Provides two ways to detect whether it is online: Navigator.online (true/false) and Online/offline events. Build the offline application Java code
//Open Application Cache
Websettingssetappcacheenabled (true) in Android;
String dir = This.getapplicationcontext (). Getdir ("cache", Context.mode_private). GetPath ();
//Set path to application cache
Websettings.setappcachepath (dir);
//Set Cached mode
Websettings.setcachemode (Websettings.load_default);
//Set maximum size for application cache
Websettings.setappcachemaxsize (1024*1024*8);
//Expanded cache capacity
Publicvoid onreachedmaxappcachesize (Long spaceneeded,
long Totalusedquota, Webstorage.quotaupdater quotaupdater) {
Quotaupdater.updatequota (spaceneeded * 2);
}
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.