● Android設備多分辨率的問題javascript
Android瀏覽器默認預覽模式瀏覽 會縮小頁面 WebView中則會以原始大小顯示css
Android瀏覽器和WebView默認爲mdpi。hdpi至關於mdpi的1.5倍 ldpi至關於0.75倍html
三種解決方式:1 viewport屬性 2 CSS控制 3 JS控制java
1 viewport屬性放在HTML的<meta>中android
Html代碼
<SPAN style="FONT-SIZE: x-small"> <head>
<title>Exmaple</title>
<meta name=」viewport」 content=」width=device-width,user-scalable=no」/>
</head></SPAN>git
meta中viewport的屬性以下web
Html代碼
<SPAN style="FONT-SIZE: x-small"> <meta name="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控制設備密度windows
爲每種密度建立獨立的樣式表(注意其中的webkit-device-pixel-ratio 3個數值對應3種分辨率)瀏覽器
Html代碼
<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.5)" href="hdpi.css" /> <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.0)" href="mdpi.css" /> <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 0.75)" href="ldpi.css" />
在一個樣式表中,指定不一樣的樣式
Html代碼
#header {
<SPAN style="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代碼
<meta name="viewport" content="target-densitydpi=device-dpi, width=device-width" />
3 JS控制
Android瀏覽器和WebView支持查詢當前設別密度的DOM特性
window.devicePixelRatio 一樣值有3個(0.75,1,1.5對應3種分辨率)
JS中查詢設備密度的方法
Js代碼 if (window.devicePixelRatio == 1.5) {
alert("This is a high-density screen");
} else if (window.devicePixelRation == 0.75) {
alert("This is a low-density screen");
}
● Android中構建HTML5應用
使用WebView控件 與其餘控件的使用方法相同 在layout中使用一個<WebView>標籤
WebView不包括導航欄,地址欄等完整瀏覽器功能,只用於顯示一個網頁
在WebView中加載Web頁面,使用loadUrl()
Java代碼 WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
注意在manifest文件中加入訪問互聯網的權限:
Xml代碼
<uses-permission android:name="android.permission.INTERNET" />
在Android中點擊一個連接,默認是調用應用程序來啓動,所以WebView須要代爲處理這個動做 經過WebViewClient
Java代碼
//設置WebViewClient
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
});
這個WebViewClient對象是能夠本身擴展的,例如
Java代碼
private class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
以後:
Java代碼
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
另外出於用戶習慣上的考慮 須要將WebView表現得更像一個瀏覽器,也就是須要能夠回退歷史記錄
所以須要覆蓋系統的回退鍵 goBack,goForward可向前向後瀏覽歷史頁面
Java代碼
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
Java代碼 WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
(這裏的webSetting用處很是大 能夠開啓不少設置 在以後的本地存儲,地理位置等之中都會使用到)
1 在JS中調用Android的函數方法
首先 須要在Android程序中創建接口
Java代碼 final class InJavaScript {
public void runOnAndroidJavaScript(final String str) {
handler.post(new Runnable() {
public void run() {
TextView show = (TextView) findViewById(R.id.textview);
show.setText(str);
}
});
}
}
Java代碼 //把本類的一個實例添加到js的全局對象window中,
//這樣就可使用windows.injs來調用它的方法
webView.addJavascriptInterface(new InJavaScript(), "injs");
在JavaScript中調用 Js代碼 function sendToAndroid(){
var str = "Cookie call the Android method from js";
windows.injs.runOnAndroidJavaScript(str);//調用android的函數
}
2 在Android中調用JS的方法
在JS中的方法: Js代碼 function getFromAndroid(str){
document.getElementByIdx_x_x_x("android").innerHTML=str;
}
在Android調用該方法 Java代碼 Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//調用javascript中的方法
webView.loadUrl("javascript:getFromAndroid('Cookie call the js function from Android')");
}
});
3 Android中處理JS的警告,對話框等 在Android中處理JS的警告,對話框等須要對WebView設置WebChromeClient對象 Java代碼
//設置WebChromeClient
webView.setWebChromeClient(new WebChromeClient(){
//處理javascript中的alert
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
//構建一個Builder來顯示網頁中的對話框
Builder builder = new Builder(MainActivity.this);
builder.setTitle("Alert");
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
return true;
};
//處理javascript中的confirm
public boolean 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() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
return true;
};
@Override //設置網頁加載的進度條 public void onProgressChanged(WebView view, int newProgress) { MainActivity.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress * 100); super.onProgressChanged(view, newProgress); } //設置應用程序的標題title public void onReceivedTitle(WebView view, String title) { MainActivity.this.setTitle(title); super.onReceivedTitle(view, title); }
});
● Android中的調試 經過JS代碼輸出log信息 Js代碼
Js代碼: console.log("Hello World");
Log信息: Console: Hello World http://www.example.com/hello.html :82
在WebChromeClient中實現onConsoleMesaage()回調方法,讓其在LogCat中打印信息 Java代碼
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
Log.d("MyApplication", message + " -- From line "
+ lineNumber + " of "
+ sourceID);
}
});
以及 Java代碼
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d("MyApplication", cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId() );
return true;
}
});
*ConsoleMessage 還包括一個 MessageLevel 表示控制檯傳遞信息類型。 您能夠用messageLevel()查詢信息級別,以肯定信息的嚴重程度,而後使用適當的Log方法或採起其餘適當的措施。
● HTML5本地存儲在Android中的應用 HTML5提供了2種客戶端存儲數據新方法: localStorage 沒有時間限制 sessionStorage 針對一個Session的數據存儲
Js代碼
<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代碼 //清空storage
localStorage.clear();
//設置一個鍵值
localStorage.setItem(「yarin」,「yangfegnsheng」);
//獲取一個鍵值
localStorage.getItem(「yarin」);
//獲取指定下標的鍵的名稱(如同Array)
localStorage.key(0);
//return 「fresh」 //刪除一個鍵值
localStorage.removeItem(「yarin」);
注意必定要在設置中開啓哦
setDomStorageEnabled(true)
在Android中進行操做
Java代碼 //啓用數據庫
webSettings.setDatabaseEnabled(true);
String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
//設置數據庫路徑
webSettings.setDatabasePath(dir);
//使用localStorage則必須打開
webSettings.setDomStorageEnabled(true);
//擴充數據庫的容量(在WebChromeClinet中實現)
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota,
long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(estimatedSize * 2);
}
在JS中按常規進行數據庫操做
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 = '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+')');
}
return false;
}
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.");
}
注意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();
}
● HTML5地理位置服務在Android中的應用 Android中
Java代碼 //啓用地理定位
webSettings.setGeolocationEnabled(true);
//設置定位的數據庫路徑
webSettings.setGeolocationDatabasePath(dir);
//配置權限(一樣在WebChromeClient中實現)
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
super.onGeolocationPermissionsShowPrompt(origin, callback);
}
在Manifest中添加權限
Xml代碼 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
HTML5中 經過navigator.geolocation對象獲取地理位置信息 經常使用的navigator.geolocation對象有如下三種方法:
Js代碼 //獲取當前地理位置
navigator.geolocation.getCurrentPosition(success_callback_function, error_callback_function, position_options)
//持續獲取地理位置
navigator.geolocation.watchPosition(success_callback_function, error_callback_function, position_options)
//清除持續獲取地理位置事件
navigator.geolocation.clearWatch(watch_position_id)
其中success_callback_function爲成功以後處理的函數,error_callback_function爲失敗以後返回的處理函數,參數position_options是配置項
在JS中的代碼 Js代碼 //定位
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;
}
}
其中position對象包含不少數據 error代碼及選項 能夠查看文檔
● 構建HTML5離線應用 須要提供一個cache manifest文件,理出全部須要在離線狀態下使用的資源 例如 Manifest代碼 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
在html標籤中聲明 <html manifest="clock.manifest">
HTML5離線應用更新緩存機制 分爲手動更新和自動更新2種 自動更新: 在cache manifest文件自己發生變化時更新緩存 資源文件發生變化不會觸發更新 手動更新: 使用window.applicationCache Js代碼 if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.update();
}
在線狀態檢測 HTML5 提供了兩種檢測是否在線的方式:navigator.online(true/false) 和 online/offline事件。
在Android中構建離線應用 Java代碼 //開啓應用程序緩存
webSettingssetAppCacheEnabled(true);
String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
//設置應用緩存的路徑
webSettings.setAppCachePath(dir);
//設置緩存的模式
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//設置應用緩存的最大尺寸
webSettings.setAppCacheMaxSize(102410248);
//擴充緩存的容量 public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { quotaUpdater.updateQuota(spaceNeeded * 2); }