Multi-Resolution for Android devices
The default Preview mode of the Android browser will narrow down the WebView page and display it in the original size.
By default, the Android browser and WebView are mdpi. Hdpi is equivalent to 1.5 times of mdpi ldpi is equivalent to 0.75 times
Three solutions: 1 viewport attribute 2 CSS Control 3 JS Control
1. Place the viewport attribute in <meta> of HTML.
Html code
Copy codeThe Code is as follows: <SPANstyle = "FONT-SIZE: x-small"> <Title> Exmaple </title>
<Metaname = "viewport" content = "width = device-width, user-scalable = no"/>
</Head> </SPAN>
The properties of viewport in meta are as follows:
Html codeCopy codeThe Code is 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 controls device Density
Create independent style sheets for each density (note that the three values webkit-device-pixel-ratio correspond to three resolutions)
Html codeCopy codeThe Code is 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 different styles.
Html codeCopy codeThe Code is 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 codeCopy codeThe Code is 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 feature of the current set density.
Window. devicePixelRatio has three values (0.75, 1, 1.5 corresponds to three resolutions)
Method for querying device density in JS
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 HTML5 applications in Android
The WebView control is used in the same way as other controls. The <WebView> label is used in layout.
WebView does not include navigation bar, address bar, and other complete browser functions. It is used to display only one web page.
Load Web pages in WebView and use loadUrl ()
Java codeCopy codeThe Code is as follows: WebView myWebView = (WebView) findViewById (R. id. webview );
MyWebView. loadUrl ("http://www.example.com ");
Note: add the Internet access permission to the manifest file:
Xml CodeCopy codeThe Code is as follows: <uses-permissionandroid: name = "android. permission. INTERNET"/>
Click a link in Android. By default, the application is called to start the process. Therefore, WebView needs to handle this action through WebViewClient.
Java codeCopy codeThe Code is 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 expanded by itself, for example
Java codeCopy codeThe Code is 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 codeCopy codeThe Code is as follows: WebView myWebView = (WebView) findViewById (R. id. webview );
MyWebView. setWebViewClient (new MyWebViewClient ());
In addition, due to user habits, WebView needs to behave more like a browser, that is, you need to be able to roll back historical records.
Therefore, it is necessary to overwrite the system's rollback key goBack. goForward can view the history page forward and backward.
Java codeCopy codeThe Code is as follows: publicboolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK) & myWebView. canGoBack (){
MyWebView. goBack ();
Returntrue;
}
Returnsuper. onKeyDown (keyCode, event );
}
Java codeCopy codeThe Code is as follows: WebView myWebView = (WebView) findViewById (R. id. webview );
WebSettings webSettings = myWebView. getSettings ();
WebSettings. setJavaScriptEnabled (true );
(Here, webSetting is very useful. It can be used in many local storage and geographical location settings)
1. Call the Android Function Method in JS
First, you need to create an interface in the Android Program
Java codeCopy codeThe Code is 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 codeCopy codeThe Code is as follows: // Add an instance of this class to the Global Object window of js,
// You can use windows. injs to call its method.
WebView. addJavascriptInterface (new InJavaScript (), "injs ");
Call Js Code in JavaScript
Function sendToAndroid (){
Var str = "Cookie call the Android method from js ";
Windows. injs. runOnAndroidJavaScript (str); // call the android Function
}
2. Call JS methods in Android
Methods In JS:
Js CodeCopy codeThe Code is as follows: function getFromAndroid (str ){
Document. getelementbyidx_x_x ("android"). innerHTML = str;
}
Java code for calling this method on AndroidCopy codeThe Code is as follows: Button button = (Button) findViewById (R. id. button );
Button. setOnClickListener (new OnClickListener (){
Publicvoid onClick (View arg0 ){
// Call the method in javascript
WebView. loadUrl ("javascript: getFromAndroid ('cookie call the js function from android ')");
}
});
3. Handle JS warnings in Android, and handle JS warnings in Android. In the dialog box, set the WebChromeClient object for WebView.
Java codeCopy codeThe Code is as follows: // set WebChromeClient
WebView. setWebChromeClient (new WebChromeClient (){
// Process alert in javascript
Publicboolean onJsAlert (WebView view, String url, String message, final JsResult result ){
// Construct a Builder to display the dialog box on the webpage
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;
};
// Process 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 the webpage loading progress bar
Publicvoid onProgressChanged (WebView view, int newProgress ){
MainActivity. this. getWindow (). setFeatureInt (Window. FEATURE_PROGRESS, newProgress * 100 );
Super. onProgressChanged (view, newProgress );
}
// Set the title of the application
Publicvoid onReceivedTitle (WebView view, String title ){
MainActivity. this. setTitle (title );
Super. onReceivedTitle (view, title );
}
});
Debugging in Android
Output log information through JS Code
Js Code
Js Code: console. log ("Hello World ");
Log info: Console: Hello World http://www.example.com/hello.html: 82
Implement the onlelemesaage () callback method in WebChromeClient to print information in LogCat.
Java codeCopy codeThe Code is 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 + ""
+ SourceID );
}
});
And Java codeCopy codeThe Code is 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 () + ""
+ Cm. sourceId ());
Returntrue;
}
});
* ConsoleMessage also contains a MessageLevel indicating the type of information transmitted on the console. You can use messageLevel () to query the information level to determine the severity of the information, and then use the appropriate Log method or take other appropriate measures.
HTML5 apps locally stored in Android
HTML5 provides two new methods for storing data on the client: localStorage has no time limit. sessionStorage stores data for a Session.
Js CodeCopy codeThe Code is 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 CodeCopy codeThe Code is as follows: // clear the storage
LocalStorage. clear ();
// Set a key value
LocalStorage. setItem ("yarin", "yangfegnsheng ");
// Obtain a key value
LocalStorage. getItem ("yarin ");
// Obtain the name of the specified underlying key (like Array)
LocalStorage. key (0 );
// Return "fresh" // delete a key value
LocalStorage. removeItem ("yarin ");
Be sure to enable it in settings.
SetDomStorageEnabled (true)
Operate Java code in Android
// Enable the database
WebSettings. setDatabaseEnabled (true );
String dir = this. getApplicationContext (). getDir ("database", Context. MODE_PRIVATE). getPath ();
// Set the database path
WebSettings. setDatabasePath (dir );
// Enable localStorage
WebSettings. setDomStorageEnabled (true );
// Expand the database capacity (implemented in WebChromeClinet)
Publicvoid onExceededDatabaseQuota (String url, String databaseIdentifier, long currentQuota,
Long estimatedSize, long totalUsedQuota, WebStorage. QuotaUpdater quotaUpdater ){
QuotaUpdater. updateQuota (estimatedSize * 2 );
}
Perform regular database operations on JS Code in Js
Function initDatabase (){
Try {
If (! Window. openDatabase ){
Alert ('databases are not supported by your browser ');
} Else {
Var shortName = 'yarindb ';
Var version = '1. 0 ';
Var displayName = 'arin 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.exe cuteSql ('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', 'arin yang', 'I am yarin'];
Transaction.exe cuteSql ("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 ('oss. Error was' + error. message + '(Code' + error. code + ')');
}
Returnfalse;
}
Function nullDataHandler (){
Console. log ("SQL Query Succeeded ");
}
Function selectAll (){
YARINDB. transaction (
Function (transaction ){
Transaction.exe cuteSql ("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 ("name"). innerHTML = "name:" + newFeature. name;
Document. getelementbyidx_x_x ("desc"). innerHTML = "desc:" + newFeature. decs;
}
}
Function updateData (){
YARINDB. transaction (
Function (transaction ){
Var data = ['fengsheng yang', 'I am fengsheng'];
Transaction.exe cuteSql ("UPDATE yarin SET name = ?, Desc =? WHERE id = 1 ", [data [0], data [1]);
}
);
SelectAll ();
}
Function ddeleteTables (){
YARINDB. transaction (
Function (transaction ){
Transaction.exe cuteSql ("drop table yarin;", [], nullDataHandler, errorHandler );
}
);
Console. log ("Table 'page _ settings' has been dropped .");
}
Pay attention to onLoad initialization.Copy codeThe Code is 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 ();
}
HTML5 location service application in Android
Java code in AndroidCopy codeThe Code is as follows: // enable location
WebSettings. setGeolocationEnabled (true );
// Set the path of the database to be located
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"/>
In HTML5, the commonly used navigator. geolocation object for obtaining geographic location information has the following three methods: Js Code
// Obtain the current geographic location
Navigator. geolocation. getCurrentPosition (success_callback_function, error_callback_function, position_options)
// Continuously obtain the geographic location
Navigator. geolocation. watchPosition (success_callback_function, error_callback_function, position_options)
// Clear events that continuously obtain geographical locations
Navigator. geolocation. clearWatch (watch_position_id)
Specifically, success_callback_function is the function to be processed after success, and error_callback_function is the processing function returned after failure. The position_options parameter is the code JS Code of the configuration item in Js.
// Locate
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 longpolling = position. coords. longpolling;
Var city = position. coords. city;
// Telnet the 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, 19.6,-4.1, M, 0000, * 5B
Document. getelementbyidx_x_x ("Latitude"). innerHTML = "latitude:" + latitude;
Document. getelementbyidx_x_x ("longbench"). innerHTML = "longbench:" + longbench;
Document. getelementbyidx_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 error code and options. You can view the document.
Build HTML5 offline applications
You need to provide a cache manifest file to identify all resources that need to be used offline.
For example, 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
Declare Js CodeCopy codeThe Code is as follows: if (window. applicationCache. status = window. applicationCache. UPDATEREADY ){
Window. applicationCache. update ();
}
Online status check HTML5 provides two ways to check whether the event is online: navigator. online (true/false) and online/offline events. Build Offline Application Java code in Android
// Enable application caching
WebSettingssetAppCacheEnabled (true );
String dir = this. getApplicationContext (). getDir ("cache", Context. MODE_PRIVATE). getPath ();
// Set the application cache path
WebSettings. setAppCachePath (dir );
// Set the cache Mode
WebSettings. setCacheMode (WebSettings. LOAD_DEFAULT );
// Set the maximum size of the application Cache
WebSettings. setAppCacheMaxSize (1024*1024*8 );
// Expand the cache capacity
Publicvoid onReachedMaxAppCacheSize (long spaceNeeded,
Long totalUsedQuota, WebStorage. QuotaUpdater quotaUpdater ){
QuotaUpdater. updateQuota (spaceNeeded * 2 );
}