android WebView load html5 introduction

  • 2020-05-09 19:21:32
  • OfStack

Multiple resolution issues with Android devices
The default preview mode of Android browser will shrink the page and the original size will be displayed in WebView
The Android browser and WebView default to mdpi. hdpi is 1.5 times mdpi and ldpi is 0.75 times
3 solutions: 1 viewport attribute 2 CSS control 3 JS control
The 1 viewport property is placed in HTML < meta > In the
Html code
 
<SPANstyle="FONT-SIZE: x-small"> <head> 
<title>Exmaple</title> 
<metaname= " viewport "  content= " width=device-width,user-scalable=no " /> 
</head></SPAN> 

The properties of viewport in meta are as follows
Html code
 
<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 controls device density
Create a separate style sheet for each density (note that the three values of webkit-device-pixel-ratio correspond to three resolutions)

Html code
 
<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 one style sheet, specify the different styles

Html code
 
#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
 
<metaname="viewport"content="target-densitydpi=device-dpi, width=device-width"/> 
[code] 
3 JS control  
Android The browser and WebView Support for querying the current setting density DOM features  
window.devicePixelRatio  Values are same 3 A ( 0.75,1,1.5 The corresponding 3 Type resolution)  
JS Query device density method  
Js code  
[code] 
if (window.devicePixelRatio == 1.5) { 
alert("This is a high-density screen"); 
} elseif (window.devicePixelRation == 0.75) { 
alert("This is a low-density screen"); 
} 

Build the HTML5 application in Android
Use one of the WebView controls in layout in the same way as the other controls < WebView > The label
WebView does not include navigation bar, address bar and other full browser functions. It is only used to display 1 web page
Load the Web page in WebView, using loadUrl()
Java code
 
WebView myWebView = (WebView) findViewById(R.id.webview); 
myWebView.loadUrl("http://www.example.com"); 

Note that access to the Internet is included in the manifest file:
Xml code
 
<uses-permissionandroid:name="android.permission.INTERNET"/> 

By clicking a link in Android, the default is to call the application to start, so WebView needs to handle this action on behalf of WebViewClient
Java code
 
// Set up the 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); 
} 
}); 

The WebViewClient object is self-extensible, for example
Java code
 
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
 
WebView myWebView = (WebView) findViewById(R.id.webview); 
myWebView.setWebViewClient(new MyWebViewClient()); 

In addition, for user habits, WebView needs to behave more like a browser, which means it needs to be able to roll back the history
So you need to override the system's back key, goBack, which can navigate back and forth through the history page
Java code
 
publicboolean onKeyDown(int keyCode, KeyEvent event) { 
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() { 
myWebView.goBack(); 
returntrue; 
} 
returnsuper.onKeyDown(keyCode, event); 
} 

Java code
 
WebView myWebView = (WebView) findViewById(R.id.webview); 
WebSettings webSettings = myWebView.getSettings(); 
webSettings.setJavaScriptEnabled(true); 

(webSetting here is very useful for turning on many Settings that can be used in local storage, location, etc.)
1 calls the function method of Android in JS
You first need to establish the interface in the Android program
Java code
 
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
 
// Take this class 1 Two instances are added to js Global object window ,  
// So you can use it windows.injs To call its methods  
webView.addJavascriptInterface(new InJavaScript(), "injs"); 
 in JavaScript In the call Js code  
function sendToAndroid(){ 
var str = "Cookie call the Android method from js"; 
windows.injs.runOnAndroidJavaScript(str);// call android The function of  
} 

2 call the JS method in Android
Methods in JS:
Js code
 
function getFromAndroid(str){ 
document.getElementByIdx_x_x_x("android").innerHTML=str; 
} 

The method Java code is called from Android
 
Button button = (Button) findViewById(R.id.button); 
button.setOnClickListener(new OnClickListener() { 
publicvoid onClick(View arg0) { 
// call javascript The methods in  
webView.loadUrl("javascript:getFromAndroid('Cookie call the js function from Android')"); 
} 
}); 

3. Android, JS, JS, Android, WebChromeClient, WebView, WebChromeClient, WebView
Java code
 
// Set up the WebChromeClient 
webView.setWebChromeClient(new WebChromeClient(){ 
// To deal with javascript In the alert 
publicboolean onJsAlert(WebView view, String url, String message, final JsResult result) { 
// build 1 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; 
}; 
// To deal with javascript In the confirm 
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 the progress bar for page loading  
publicvoid onProgressChanged(WebView view, int newProgress) { 
MainActivity.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress * 100); 
super.onProgressChanged(view, newProgress); 
} 
// Sets the title of the application title 
publicvoid onReceivedTitle(WebView view, String title) { 
MainActivity.this.setTitle(title); 
super.onReceivedTitle(view, title); 
} 
}); 

Debugging in Android
Output log information through the 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 the message in LogCat
Java code
 
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 the Java code
 
<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> 
8
*ConsoleMessage also includes an MessageLevel for console transfer information type. You can query the information level with messageLevel() to determine the severity of the information, then use the appropriate Log method or take other appropriate action.
Application of HTML5 local storage in Android
HTML5 provides two new ways to store data on the client side: localStorage has no time limit sessionStorage for one Session data store
Js code
 
<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> 
9
WebStorage API:
Js code
 
<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"/> 
0
Notice the initialization in onLoad
 
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(); 
} 

Application of HTML5 location services in Android
Java code in Android
 
// Enable geolocation  
webSettings.setGeolocationEnabled(true); 
// Set the database path to the location  
webSettings.setGeolocationDatabasePath(dir); 
// Configure permissions (also in WebChromeClient In the implementation)  
publicvoid onGeolocationPermissionsShowPrompt(String origin, 
GeolocationPermissions.Callback callback) { 
callback.invoke(origin, true, false); 
super.onGeolocationPermissionsShowPrompt(origin, callback); 
} 
 in Manifest Add permissions in  Xml code  
<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/> 
HTML5 In the   through navigator.geolocation Object to get geographical location information   The commonly used navigator.geolocation Objects have the following 3 Methods:  Js code  
// Gets the current geographic location  
navigator.geolocation.getCurrentPosition(success_callback_function, error_callback_function, position_options) 
// Keep getting location  
navigator.geolocation.watchPosition(success_callback_function, error_callback_function, position_options) 
// Clears the persistent geolocation event  
navigator.geolocation.clearWatch(watch_position_id) 
 Among them success_callback_function Is the function processed after success, error_callback_function Is the handler function returned after the failure, parameter position_options Is the configuration items   in JS The code in 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; 
} 
} 

The position object contains a lot of data and the error code and options to view the documentation
Build the HTML5 offline application
You need to provide an cache manifest file to sort out all the resources that need to be used offline
For example, the Manifest code
CACHE MANIFEST
This is a comment
images/sound-icon.png
images/background.png
clock.html
clock.css
clock.js
NETWORK:
test.cgi
CACHE:
style/default.css
FALLBACK:
/files/projects /projects
Declared in the html tag < html manifest="clock.manifest" > Offline application of HTML5 there are two automatic update mechanisms: manual update and automatic update: update the cache resource file when the cache manifest file itself changes without triggering the update manual update: use window.applicationCache
Js code
 
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) { 
window.applicationCache.update(); 
} 
 On line status detection  HTML5  There are two ways to check if you are online: navigator.online ( true/false )   and  online/offline Events. in Android Build offline applications in Java code  
// Turn on the application cache  
webSettingssetAppCacheEnabled(true); 
String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath(); 
// Sets the path to apply the cache  
webSettings.setAppCachePath(dir); 
// Set the cache mode  
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); 
// Sets the maximum size of the application cache  
webSettings.setAppCacheMaxSize(1024*1024*8); 
// Expand the capacity of the cache  
publicvoid onReachedMaxAppCacheSize(long spaceNeeded, 
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { 
quotaUpdater.updateQuota(spaceNeeded * 2); 
} 

Related articles: