利用HTML5开发Android

发布日期:2016-10-15查看人数:
Android设备多分辨率的问题

A ndroid浏览器默认预览模式浏览 会缩小页面 WebView中则会以原始大小显示

A ndroid浏览器和WebView默认为mdpihdpi相当于mdpi1.5倍ldpi相当于0.75倍

三种解决方式1viewport属性 2CSS控制 3JS控制

1viewport属性放在HTML<meta>中
Html代码  

<SPA N style="FONT-SIZE: x-small">   <head>   
        <title>Exmaple</title>   
        <meta name=viewport content=width=device-width,< 
<SPA N style="FONT-SIZE: x-small">   <head>   
        <title>Exmaple</title>   
        <meta name=viewport content=width=device-width.user-scalable=no/>   
    </head></SPA N>  
<head><title>Exmaple</title><metaname=viewportcontent=width=device-width,user-scalable=no/></head>
meta中viewport属性如下

Html代码  

<SPA N style="FONT-SIZE: x-small">   <meta name="viewport"  
        content="  
            height = [pixel_value | device-height] ,< 
<SPA N 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]  
        "  
    /></SPA N>  
<metaname="viewport"content="height=[pixel_valu|device-height],width=[pixel_valu|device-width],initial-scal=float_valu,minimum-scal=float_valu,maximum-scal=float_valu,user-scal=[ye|no],target-densitydpi=[dpi_valu|device-dpi|high-dpi|medium-dpi|low-dpi]"/>

 

 

2CSS控制设备密度

为每种密度创建独立的样式表(注意其中的webkit-device-pixel-ratio3个数值对应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" />  
<linkrel="stylesheet"media="screenand-webkit-device-pixel-ratio:1.5"href="hdpi.css"/><linkrel="stylesheet"media="screenand-webkit-device-pixel-ratio:1.0"href="mdpi.css"/><linkrel="stylesheet"media="screenand-webkit-device-pixel-ratio:0.75"href="ldpi.css"/>

指定不同的样式一个样式表中。
Html代码  

#header {   
 <SPA N style="WHITE-SPA CE: pre">        </SPA N> background:urlmedium-density-image.png;   
}  
@media screen and -webkit-device-pixel-ratio: 1.5 {   
    // CSS for high-density screens   
    #header {   
        background:urlhigh-density-image.png;   
    }   
}   
@media screen and -webkit-device-pixel-ratio: 0.75 {   
    // CSS for low-density screens   
    #header {   
        background:urllow-density-image.png;   
    }   
}  
#header{background:urlmedium-density-image.png;}@mediascreenand-webkit-device-pixel-ratio:1.5{//CSSforhigh-densscreen#header{background:urlhigh-density-image.png;}}@mediascreenand-webkit-device-pixel-ratio:0.75{//CSSforlow-densscreen#header{background:urllow-density-image.png;}}

Html代码  

<meta name="viewport" content="target-densitydpi=device-dpi,<<Html代码  
<meta name="viewport" content="target-densitydpi=device-dpi. width=device-width" />  
<metaname="viewport"content="target-densitydpi=device-dpi,width=device-width"/>

 
 3JS控制

A ndroid浏览器和WebView支持查询当前设别密度的DOM特性

1,window.devicePixelRatio同样值有3个(0.75.1.5对应3种分辨率)

JS中查询设备密度的方法


J代码 

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";  
}  
ifwindow.devicePixelRatio==1.5{alert"Thiisahigh-densscreen";}elsifwindow.devicePixelR==0.75{alert"Thiisalow-densscreen";}

 
Android中构建HTML5应用

使用WebView控件 与其他控件的使用方法相同在layout中使用一个<WebView>标签

地址栏等完整浏览器功能,WebView不包括导航栏。只用于显示一个网页

使用loadUrl



Java代码 

WebView myWebView = WebView findViewByIdR.id.webview;  
myWebView.loadUrl"http://www.example.com";  
WebViewmyWebView=WebViewfindViewByIdR.id.webview;myWebView.loadUrl"http://www.example.com";

注意在manifest文件中加入访问互联网的权限:


Xml代码  

<uses-permission android:name="android.permission.INTERNET" />  
<uses-permissandroid:name="android.permission.INTERNET"/>

 
Android中点击一个链接,< 

<uses-permission android:name="android.permission.INTERNET" />  
<uses-permissandroid:name="android.permission.INTERNET"/>

 通过WebViewClient

Java代码  

//设置WebViewClient  
webView.setWebViewClinew WebViewCli{     
    public boolean shouldOverrideUrlLoadingWebView view,< 
//设置WebViewClient  
webView.setWebViewClinew WebViewCli{     
    public boolean shouldOverrideUrlLoadingWebView view. String url {     
        view.loadUrlurl;     
        return true;     
    }    
    public void onPageFinishWebView view, String url {  
            super.onPageFinishview, url;  
    }  
    public void onPageStartWebView view, String url, Bitmap favicon {  
        super.onPageStartview, url, favicon;  
    }  
};  
//设置WebViewClientwebView.setWebViewClinewWebViewCli{publicbooleanshouldOverrideUrlLoadingWebViewview,Stringurl{view.loadUrlurl;returntrue;}publicvoidonPageFinishWebViewview,Stringurl{super.onPageFinishview,url;}publicvoidonPageStartWebViewview,Stringurl,Bitmapfavicon{super.onPageStartview,url,favicon;}};

这个WebViewCli对象是可以自己扩展的例如
Java代码  

private class MyWebViewClient extends WebViewClient {  
    public boolean shouldOverrideUrlLoadingWebView view,< 
private class MyWebViewClient extends WebViewClient {  
    public boolean shouldOverrideUrlLoadingWebView view. String url {  
        if Uri.parsurl.getHost.equal"www.example.com" {  
            return false;  
        }  
        Intent intent = new IntIntent.A CTION_VIEW, Uri.parsurl;  
    startA ctivintent;  
    return true;  
    }  
}  
privatclassMyWebViewCliextendWebViewCli{publicbooleanshouldOverrideUrlLoadingWebViewview,Stringurl{ifUri.parsurl.getHost.equal"www.example.com"{returnfalse;}Intentintent=newIntentIntent.A CTION_VIEW,Uri.parsurl;startA ctivintent;returntrue;}}
 
之后:

Java代码  

WebView myWebView = WebView findViewByIdR.id.webview;  
myWebView.setWebViewClinew MyWebViewCli;  
WebViewmyWebView=WebViewfindViewByIdR.id.webview;myWebView.setWebViewClinewMyWebViewCli;

另外出于用户习惯上的考虑 需要将WebView表示得更像一个浏览器,< 

WebView myWebView = WebView findViewByIdR.id.webview;  
myWebView.setWebViewClinew MyWebViewCli;  
WebViewmyWebView=WebViewfindViewByIdR.id.webview;myWebView.setWebViewClinewMyWebViewCli;

<另外出于用户习惯上的考虑 需要将WebView表示得更像一个浏览器。也就是需要可以回退历史记录

因此需要覆盖系统的回退键goBackgoForward可向前向后浏览历史页面



Java代码  

public boolean onKeyDownint keyCode,< 
public boolean onKeyDownint keyCode. KeyEvent ev {  
    if keyCode == KeyEvent.KEYCODE_BA CK && myWebView.canGoBack {  
        myWebView.goBack;  
        return true;  
    }  
    return super.onKeyDownkeyCode, ev;  
}  
publicbooleanonKeyDownintkeyCode,KeyEventevent{ifkeyCod==KeyEvent.KEYCODE_BA CK&&myWebView.canGoBack{myWebView.goBack;returntrue;}returnsuper.onKeyDownkeyCode,event;}

Android与JS之间的互相调用交互

就可以在两者间建立接口进行调用WebView默认是禁用JavaScript启用后。

Java代码 

WebView myWebView = WebView findViewByIdR.id.webview;  
WebSettings webSettings = myWebView.getSet;  
webSettings.setJavaScriptEntrue;  
WebViewmyWebView=WebViewfindViewByIdR.id.webview;WebSetwebSet=myWebView.getSet;webSettings.setJavaScriptEntrue;


 

地理位置等之中都会使用到这里的webSet用处非常大 可以开启很多设置 之后的外地存储。


1JS中调用Android函数方法

首先 需要Android顺序中建立接口

Java代码 

final class InJavaScript {  
       public void runOnA ndroidJavaScriptfinal String str {  
        handler.postnew Runn {  
               public void run {   
                   TextView show = TextView findViewByIdR.id.textview;  
                   show.setTextstr;  
               }  
           };  
       }  
   }  
finalclassInJavaScript{publicvoidrunOnA ndroidJavaScriptfinalStringstr{handler.postnewRunnabl{publicvoidrun{TextViewshow=TextViewfindViewByIdR.id.textview;show.setTextstr;}};}}
Java代码 

//把本类的一个实例添加到js全局对象window中,  
//这样就可以使用windows.inj来调用它方法  
webView.addJavascriptInterfacnew InJavaScript, 

<<
//把本类的一个实例添加到js全局对象window中。 "injs";  
//把本类的一个实例添加到js全局对象window中,//这样就可以使用windows.inj来调用它方法webView.addJavascriptInterfacnewInJavaScript,"injs";



JavaScript中调用

J代码 

function sendToA ndroid{  
        var str = "Cookie call the A ndroid method from js";  
        windows.injs.runOnA ndroidJavaScriptstr;//调用android函数  
}  
functionsendToA ndroid{varstr="CookicalltheAndroidmethodfromjs";windows.injs.runOnA ndroidJavaScriptstr;//调用android函数}


2Android中调用JS方法

JS中的方法



J代码 

function getFromA ndroidstr{  
        document.getElementByIdx_x_x_x"android".innerHTML=str;  
}  
functiongetFromA ndroidstr{document.getElementByIdx_x_x_x"android".innerHTML=str;}

 

A ndroid调用该方法





Java代码 

Button button = Button findViewByIdR.id.button;  
       button.setOnClickListennew OnClickListen {  
       public void onClickView arg0 {  
            //调用javascript中的方法  
           webView.loadUrl"javascript:getFromA ndroid'Cookie call the js function from A ndroid'";  
       }  
   };  
Buttonbutton=ButtonfindViewByIdR.id.button;button.setOnClickListennewOnClickListen{publicvoidonClickViewarg0{//调用javascript中的方法webView.loadUrl"javascript:getFromA ndroid'CookicallthejsfunctionfromAndroid'";}};

 

对话框等3Android中处理JS警告。>

对话框等需要对WebView设置WebChromeCli对象





Java代码  

//设置WebChromeClient  
webView.setWebChromeClinew WebChromeCli{  
    //处置javascript中的alert  
    public boolean onJsA lertWebView view,

<<
//设置WebChromeClient  
webView.setWebChromeClinew WebChromeCli{  
    //处置javascript中的alert  
    public boolean onJsA lertWebView view. String url, String message, final JsResult result {  
        //构建一个Builder来显示网页中的对话框  
        Builder builder = new BuildMainA ctivity.this;  
        builder.setTitl"A lert";  
        builder.setMessagmessag;  
        builder.setPositiveButtonandroid.R.string.ok,  
            new A lertDialog.OnClickListen {  
                public void onClickDialogInterface dialog, int which {  
                    result.confirm;  
                }  
            };  
        builder.setCancelfalse;  
        builder.cr;  
        builder.show;  
        return true;  
    };  
    //处置javascript中的confirm  
    public boolean onJsConfirmWebView view, String url, String message, final JsResult result {  
        Builder builder = new BuildMainA ctivity.this;  
        builder.setTitl"confirm";  
        builder.setMessagmessag;  
        builder.setPositiveButtonandroid.R.string.ok,  
            new A lertDialog.OnClickListen {  
                public void onClickDialogInterface dialog, int which {  
                    result.confirm;  
                }  
            };  
        builder.setNegativeButtonandroid.R.string.cancel,  
            new DialogInterface.OnClickListen {  
                public void onClickDialogInterface dialog, int which {  
                    result.cancel;  
                }  
            };  
        builder.setCancelfalse;  
        builder.cr;  
        builder.show;  
        return true;  
    };  
          
    @Override  
    //设置网页加载的进度条  
    public void onProgressChangWebView view, int newProgress {  
        MainA ctivity.this.getWindow.setFeatureIntWindow.FEA TURE_PROGRESS, newProgress * 100;  
        super.onProgressChangview, newProgress;  
    }  
  
    //设置应用顺序的标题title  
    public void onReceivedTitlWebView view, String titl {  
        MainA ctivity.this.setTitltitl;  
        super.onReceivedTitlview, titl;  
    }  
};  
//设置WebChromeClientwebView.setWebChromeClinewWebChromeCli{//处置javascript中的alertpublicbooleanonJsA lertWebViewview,Stringurl,Stringmessage,finalJsResultresult{//构建一个Builder来显示网页中的对话框Builderbuilder=newBuilderMainA ctivity.thi;builder.setTitl"A lert";builder.setMessagmessag;builder.setPositiveButtonandroid.R.string.ok,newAlertDialog.OnClickListen{publicvoidonClickDialogInterfacdialog,intwhich{result.confirm;}};builder.setCancelfals;builder.cr;builder.show;returntrue;};//处置javascript中的confirmpublicbooleanonJsConfirmWebViewview,Stringurl,Stringmessage,finalJsResultresult{Builderbuilder=newBuilderMainA ctivity.thi;builder.setTitl"confirm";builder.setMessagmessag;builder.setPositiveButtonandroid.R.string.ok,newAlertDialog.OnClickListen{publicvoidonClickDialogInterfacdialog,intwhich{result.confirm;}};builder.setNegativeButtonandroid.R.string.cancel,newDialogInterface.OnClickListen{publicvoidonClickDialogInterfacdialog,intwhich{result.cancel;}};builder.setCancelfals;builder.cr;builder.show;returntrue;};@Override//设置网页加载的进度条publicvoidonProgressChangWebViewview,intnewProgress{MainA ctivity.this.getWindow.setFeatureIntWindow.FEA TURE_PROGRESS,newProgress*100;super.onProgressChangview,newProgress;}//设置应用顺序的标题titlepublicvoidonReceivedTitlWebViewview,Stringtitl{MainA ctivity.this.setTitltitl;super.onReceivedTitlview,titl;}};

 

Android中的调试

通过JS代码输出log信息





J代码  

J代码: console.log"Hello World";  
Log信息: Console: Hello World http://www.example.com/hello.html :82   
Js代码:console.log"HelloWorld";Log信息:Console:HelloWorldhttp://www.example.com/hello.html:82

 

让其在LogCat中打印信息WebChromeCli中实现onConsoleMesaag回调方法。





Java代码  

WebView myWebView = WebView findViewByIdR.id.webview;  
myWebView.setWebChromeClinew WebChromeCli {  
    public void onConsoleMessagString message,

<< 
WebView myWebView = WebView findViewByIdR.id.webview;  
myWebView.setWebChromeClinew WebChromeCli {  
    public void onConsoleMessagString message. int lineNumber, String sourceID {  
        Log.d"MyA pplication", message + " -- From line "  
            + lineNumber + " of "  
            + sourceID;  
    }  
};  
WebViewmyWebView=WebViewfindViewByIdR.id.webview;myWebView.setWebChromeClinewWebChromeCli{publicvoidonConsoleMessagStringmessage,intlineNumber,StringsourceID{Log.d"MyA pplication",messag+"--Fromline"+lineNumb+"of"+sourceID;}};


以及





Java代码  

WebView myWebView = WebView findViewByIdR.id.webview;  
myWebView.setWebChromeClinew WebChromeCli {  
    public boolean onConsoleMessagConsoleMessage cm {  
        Log.d"MyA pplication",

<<
WebView myWebView = WebView findViewByIdR.id.webview;  
myWebView.setWebChromeClinew WebChromeCli {  
    public boolean onConsoleMessagConsoleMessage cm {  
        Log.d"MyA pplication". cm.messag + " -- From line "  
            + cm.lineNumber + " of "  
            + cm.sourceId ;  
        return true;  
    }  
};  
WebViewmyWebView=WebViewfindViewByIdR.id.webview;myWebView.setWebChromeClinewWebChromeCli{publicbooleanonConsoleMessagConsoleMessagcm{Log.d"MyA pplication",cm.messag+"--Fromline"+cm.lineNumb+"of"+cm.sourceId;returntrue;}};

 

以确定信息的严重水平,*ConsoleMessag还包括一个 MessageLevel表示控制台传送信息类型。您可以用messageLevel查询信息级别。然后使用适当的Log方法或采取其他适当的措施。

 

HTML5外地存储在Android中的应用

HTML5提供了2种客户端存储数据新方法

localStorag没有时间限制

sessionStorag针对一个Session数据存储

J代码 

<script type="text/javascript">   
    localStorage.lastname="Smith";   
    document.writlocalStorage.lastnam;   
</script>   
<script type="text/javascript">   
    sessionStorage.lastname="Smith";   
    document.writsessionStorage.lastnam;  
</script>   
<scripttype="text/javascript">localStorage.lastname="Smith";document.writlocalStorage.lastnam;</script><scripttype="text/javascript">sessionStorage.lastname="Smith";document.writsessionStorage.lastnam;</script>
 
WebStoragAPI:

J代码 

//清空storage  
localStorage.clear;  
//设置一个键值  
localStorage.setItemyarin, 

<<
//清空storage  
localStorage.clear;  
//设置一个键值  
localStorage.setItemyarin.yangfegnsheng;  
//获取一个键值  
localStorage.getItemyarin;   
//获取指定下标的键的名称(如同Arrai  
localStorage.kei0;   
//return fresh //删除一个键值  
localStorage.removeItemyarin;  
注意一定要在设置中开启哦   
setDomStorageEntrue  
//清空storagelocalStorage.clear;//设置一个键值localStorage.setItemyarin,yangfegnsheng;//获取一个键值localStorage.getItemyarin;//获取指定下标的键的名称(如同ArrailocalStorage.kei0;//returnfresh//删除一个键值localStorage.removeItemyarin;注意一定要在设置中开启哦setDomStorageEntrue

A ndroid中进行操作


Java代码 

//启用数据库  
webSettings.setDatabaseEntrue;    
String dir = this.getA pplicationContext.getDir"database", 

<<
//启用数据库  
webSettings.setDatabaseEntrue;    
String dir = this.getA pplicationContext.getDir"database". Context.MODE_PRIVA TE.getPath;  
//设置数据库路径  
webSettings.setDatabasePathdir;  
//使用localStorag则必须打开  
webSettings.setDomStorageEntrue;  
//扩充数据库的容量(WebChromeClinet中实现)  
public void onExceededDatabaseQuotaString url, String databaseIdentifier, long currentQuota,   
        long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater {  
    quotaUpdater.updateQuotaestimatedSize * 2;  
}  
//启用数据库webSettings.setDatabaseEntrue;Stringdir=this.getA pplicationContext.getDir"database",Context.MODE_PRIVA TE.getPath;//设置数据库路径webSettings.setDatabasePathdir;//使用localStorag则必须打开webSettings.setDomStorageEntrue;//扩充数据库的容量(WebChromeClinet中实现)publicvoidonExceededDatabaseQuotaStringurl,StringdatabaseIdentifier,longcurrentQuota,longestimatedSize,longtotalUsedQuota,WebStorage.QuotaUpdatquotaUpdat{quotaUpdater.updateQuotaestimatedS*2;}

JS中按惯例进行数据库操作


J代码 

function initDatabas {  
try {  
    if !window.openDatabas {  
        alert'Databases are not supported by your browser';  
    } else {  
        var shortName = 'YA RINDB';  
        var version = '1.0';  
        var displayName = 'yarin db';  
        var maxSize = 100000; // in bytes  
        YA RINDB = openDatabasshortName, 

<<
function initDatabas {  
try {  
    if !window.openDatabas {  
        alert'Databases are not supported by your browser';  
    } else {  
        var shortName = 'YA RINDB';  
        var version = '1.0';  
        var displayName = 'yarin db';  
        var maxSize = 100000; // in bytes  
        YA RINDB = openDatabasshortName. version, displayName, maxS;  
        createT;  
        selectA l;  
    }  
} catche {  
    if e == 2 {  
        // Version mismatch.  
        console.log"Invalid database version.";  
    } else {  
        console.log"Unknown error "+ e +".";  
    }  
    return;  
}   
}  
  
function createT{  
    YA RINDB.transact  
        function transact {  
            transaction.executeSql'CREA TE TA BLE IF NOT EXISTS yarinid INTEGER NOT NULL PRIMA RY KEY, name TEXT NOT NULL,desc TEXT NOT NULL;', [], nullDataHandler, errorHandl;  
        }  
    ;  
    insertData;  
}  
  
function insertData{  
    YA RINDB.transact  
        function transact {  
        //Starter data when page is initialized  
        var data = ['1','yarin yang','I am yarin'];    
          
        transaction.executeSql"INSERT INTO yarinid, name, desc VA LUES ?, ?, ?", [data[0], data[1], data[2]];  
        }  
    ;    
}  
  
function errorHandltransaction, 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 nullDataHandl{  
    console.log"SQL Query Succeeded";  
}  
  
function selectA l{   
    YA RINDB.transact  
        function transact {  
            transaction.executeSql"SELECT * FROM yarin;", [], dataSelectHandler, errorHandler;  
        }  
    ;    
}  
  
function dataSelectHandltransaction, result{  
    // Handle the results  
    for var i=0; i<results.rows.length; i++ {  
        var row = results.rows.itemi;  
        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{  
    YA RINDB.transact  
        function transact {  
            var data = ['fengsheng yang','I am fengsheng'];   
            transaction.executeSql"UPDA TE yarin SET name=?, desc=? WHERE id = 1", [data[0], data[1]];  
        }  
    ;    
    selectA l;  
}  
  
function ddeleteT{  
    YA RINDB.transact  
        function transact {  
            transaction.executeSql"DROP TA BLE yarin;", [], nullDataHandler, errorHandler;  
        }  
    ;  
    console.log"Table 'page_settings' has been dropped.";  
}  
注意onLoad中的初始化工作   
function initLocalStorag{  
    if window.localStorag {  
        textarea.addEventListen"keyup", function {  
            window.localStorage["value"] = this.value;  
            window.localStorage["time"] = new D.getTim;  
        }, false;  
    } else {  
        alert"LocalStorage are not supported in this browser.";  
    }  
}  
  
window.onload = function {  
    initDatabas;  
    initLocalStorag;  
}  
functioninitDatabas{try{if!window.openDatabas{alert'Databasarnotsupportbyyourbrowser';}els{varshortNam='YA RINDB';varversion='1.0';vardisplayNam='yarindb';varmaxSiz=100000;//inbytesYA RINDB=openDatabasshortName,version,displayName,maxSiz;createT;selectA l;}}catche{ife==2{//Versionmismatch.console.log"Invaliddatabasversion.";}els{console.log"Unknownerror"+e+".";}return;}}functioncreateT{YA RINDB.transactfunctiontransact{transaction.executeSql'CREA TETA BLEIFNOTEXISTSyarinidINTEGERNOTNULLPRIMA RYKEY,nameTEXTNOTNULL,descTEXTNOTNULL;',[],nullDataHandler,errorHandl;};insertData;}functioninsertData{YA RINDB.transactfunctiontransact{//Starterdatawhenpageisinitializedvardata=['1','yarinyang','Iamyarin'];transaction.executeSql"INSERTINTOyarinid,name,descVA LUES?,?,?",[data[0],data[1],data[2]];};}functionerrorHandltransaction,error{iferror.code==1{//DBTablalreadiexists}els{//Errorisahuman-readstring.console.log'Oops.Errorwa'+error.message+'Code'+error.code+'';}returnfalse;}functionnullDataHandl{console.log"SQLQueriSucceeded";}functionselectA l{YA RINDB.transactfunctiontransact{transaction.executeSql"SELECT*FROMyarin;",[],dataSelectHandler,errorHandl;};}functiondataSelectHandltransaction,result{//Handltheresultsforvari=0;i<results.rows.length;i++{varrow=results.rows.itemi;varnewFeatur=newObject;newFeature.nam=row['name'];newFeature.dec=row['desc'];document.getElementByIdx_x_x_x"name".innerHTML="name:"+newFeature.name;document.getElementByIdx_x_x_x"desc".innerHTML="desc:"+newFeature.decs;}}functionupdateData{YA RINDB.transactfunctiontransact{vardata=['fengshengyang','Iamfengsheng'];transaction.executeSql"UPDA TEyarinSETname=?,desc=?WHEREid=1",[data[0],data[1]];};selectA l;}functionddeleteT{YA RINDB.transactfunctiontransact{transaction.executeSql"DROPTA BLEyarin;",[],nullDataHandler,errorHandl;};console.log"Tabl'page_settings'habeendropped.";}注意onLoad中的初始化工作functioninitLocalStorag{ifwindow.localStorag{textarea.addEventListen"keyup",function{window.localStorage["value"]=this.value;window.localStorage["time"]=newDate.getTim;},fals;}els{alert"LocalStoragarnotsupportinthibrowser.";}}window.onload=function{initDatabas;initLocalStorag;}

HTML5地理位置服务在Android中的应用

A ndroid中

Java代码 

//启用地理定位  
webSettings.setGeolocationEntrue;  
//设置定位的数据库路径  
webSettings.setGeolocationDatabasePathdir;  
  
//配置权限(同样在WebChromeCli中实现)  
public void onGeolocationPermissionsShowPromptString origin, 

<<
//启用地理定位  
webSettings.setGeolocationEntrue;  
//设置定位的数据库路径  
webSettings.setGeolocationDatabasePathdir;  
  
//配置权限(同样在WebChromeCli中实现)  
public void onGeolocationPermissionsShowPromptString origin.   
               GeolocationPermissions.Callback callback {  
    callback.invokorigin, true, false;  
    super.onGeolocationPermissionsShowPromptorigin, callback;  
}  
//启用地理定位webSettings.setGeolocationEntrue;//设置定位的数据库路径webSettings.setGeolocationDatabasePathdir;//配置权限(同样在WebChromeCli中实现)publicvoidonGeolocationPermissionsShowPromptStringorigin,GeolocationPermissions.Callbackcallback{callback.invokorigin,true,fals;super.onGeolocationPermissionsShowPromptorigin,callback;}
 
Manifest中添加权限

Xml代码 

<uses-permission android:name="android.permission.A CCESS_FINE_LOCA TION" />  
<uses-permission android:name="android.permission.A CCESS_COA RSE_LOCA TION" />  
<uses-permissandroid:name="android.permission.A CCESS_FINE_LOCA TION"/><uses-permissandroid:name="android.permission.A CCESS_COA RSE_LOCA TION"/>

HTML5中 通过navigator.geoloc对象获取地理位置信息

常用的navigator.geoloc对象有以下三种方法:

J代码 

//获取当前地理位置  
navigator.geolocation.getCurrentPositsuccess_callback_function, 

<<
//获取当前地理位置  
navigator.geolocation.getCurrentPositsuccess_callback_function. error_callback_function, position_opt  
//继续获取地理位置  
navigator.geolocation.watchPositsuccess_callback_function, error_callback_function, position_opt  
//清除继续获取地理位置事件  
navigator.geolocation.clearWatchwatch_position_id  
//获取当前地理位置navigator.geolocation.getCurrentPositsuccess_callback_function,error_callback_function,position_opt//继续获取地理位置navigator.geolocation.watchPositsuccess_callback_function,error_callback_function,position_opt//清除继续获取地理位置事件navigator.geolocation.clearWatchwatch_position_id

error_callback_funct为失败之后返回的处置函数,其中success_callback_funct为胜利之后处置的函数。参数position_opt配置项

JS中代码

J代码 

//定位  
function get_loc {  
    if navigator.geoloc {  
        navigator.geolocation.getCurrentPositionshow_map,

<<
//定位  
function get_loc {  
    if navigator.geoloc {  
        navigator.geolocation.getCurrentPositionshow_map.handle_error,{enableHighA ccuracy:false,maximumA ge:1000,timeout:15000};  
    } else {  
        alert"Your browser does not support HTML5 geoLocation";  
    }  
}  
      
function show_mapposit {  
    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_errorerr {  
    switch err.cod {  
    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;  
    }  
}  
//定位functionget_loc{ifnavigator.geoloc{navigator.geolocation.getCurrentPositshow_map,handle_error,{enableHighA ccuracy:false,maximumA ge:1000,timeout:15000};}els{alert"YourbrowserdoenotsupportHTML5geoLocation";}}functionshow_mapposit{varlatitud=position.coords.latitude;varlongitud=position.coords.longitude;varciti=position.coords.city;//telnetlocalhost5554//geofix-82.41162928.054553//geofix-121.4535646.511194392//geonmea$GPGGA ,001431.092,0118.2653,N,10351.1359,E,0,00,,-19.6,M,4.1,M,,0000*5Bdocument.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;}functionhandle_errorerr{switcherr.cod{case1:alert"permissdenied";break;case2:alert"thenetworkisdownorthepositsatellitcan'tbecontacted";break;case3:alert"timeout";break;default:alert"unknownerror";break;}}


 

其中posit对象包括很多数据 error代码及选项 可以检查文档


构建HTML5离线应用

理出所有需要在离线状态下使用的资源需要提供一个cachmanifest文件。

例如





Manifest代码 

CA CHE MA NIFEST   
#这是注释   
images/sound-icon.png  
images/background.png  
clock.html   
clock.css   
clock.js    
  
NETWORK:   
test.cgi  
  
CA CHE:   
style/default.css  
  
FA LLBA CK:   
/files/projects /projects  
CA CHEMA NIFEST#这是注释images/sound-icon.pngimages/background.pngclock.htmlclock.cssclock.jNETWORK:test.cgiCA CHE:style/default.cssFA LLBA CK:/files/project/projects


 

html标签中声明 <htmlmanifest="clock.manifest"> 


HTML5离线应用更新缓存机制

分为手动更新和自动更新2种

自动更新:

cachmanifest文件自身发生变化时更新缓存 资源文件发生变化不会触发更新

手动更新:

使用window.applicationCache





J代码 

if window.applicationCache.status == window.applicationCache.UPDA TEREA DY {   
    window.applicationCache.upd;  
}   
ifwindow.applicationCache.statu==window.applicationCache.UPDA TEREA DY{window.applicationCache.upd;} 


线状态检测

HTML5提供了两种检测是否在线的方式:navigator.onlintrue/fals和online/offlin事件。


Android中构建离线应用

Java代码 

//开启应用顺序缓存  
webSettingssetA ppCacheEntrue;  
String dir = this.getA pplicationContext.getDir"cache",

<<
//开启应用顺序缓存  
webSettingssetA ppCacheEntrue;  
String dir = this.getA pplicationContext.getDir"cache". Context.MODE_PRIVA TE.getPath;  
//设置应用缓存的路径  
webSettings.setA ppCachePathdir;  
//设置缓存的模式  
webSettings.setCacheModWebSettings.LOA D_DEFA ULT;  
//设置应用缓存的最大尺寸  
webSettings.setA ppCacheMaxS1024*1024*8;  
  
//扩充缓存的容量  
public void onReachedMaxA ppCacheSizelong spaceNeeded,  
            long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater {  
    quotaUpdater.updateQuotaspaceNeeded * 2;  
}  
//开启应用顺序缓存webSettingssetA ppCacheEntrue;Stringdir=this.getA pplicationContext.getDir"cache",Context.MODE_PRIVA TE.getPath;//设置应用缓存的路径webSettings.setA ppCachePathdir;//设置缓存的模式webSettings.setCacheModWebSettings.LOA D_DEFA ULT;//设置应用缓存的最大尺寸webSettings.setA ppCacheMaxS1024*1024*8;//扩充缓存的容量publicvoidonReachedMaxA ppCacheSizelongspaceNeeded,longtotalUsedQuota,WebStorage.QuotaUpdatquotaUpdat{quotaUpdater.updateQuotaspaceNeed