利用HTML5开发Android笔记(下篇)
?
资源来自于www.mhtml5.com 杨丰盛老师成都场的PPT分享 一个很简明的demo 可以作为入门基础
学习的过程中做了点笔记 整理如下 虽然内容比较简单 但是数量还是比较多的 所以分了3篇
(上)包括Android设备多分辨率的问题,Android中构建HTML5应用程序基础
(中)包括Android与JS之间的互动,Android处理JS的警告对话框等,Android中的调试
(下)包括本地储存在Android中的应用,地理位置的应用,离线应用的构建
—————————————————————————————— 分割线 ————————————————————————————————————————
进入正题
● HTML5本地存储在Android中的应用
HTML5提供了2种客户端存储数据新方法:
localStorage 没有时间限制
sessionStorage 针对一个Session的数据存储
?
<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:
?
//清空storagelocalStorage.clear();//设置一个键值localStorage.setItem(“yarin”,“yangfegnsheng”);//获取一个键值localStorage.getItem(“yarin”); //获取指定下标的键的名称(如同Array)localStorage.key(0); //return “fresh” //删除一个键值localStorage.removeItem(“yarin”);注意一定要在设置中开启哦setDomStorageEnabled(true)
?
在Android中进行操作
?
//启用数据库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中按常规进行数据库操作
?
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 initializedvar 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 resultsfor (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.getElementById("name").innerHTML="name:"+newFeature.name;document.getElementById("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中
?
//启用地理定位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中添加权限
?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
?
?
HTML5中 通过navigator.geolocation对象获取地理位置信息
常用的navigator.geolocation对象有以下三种方法:
?
//获取当前地理位置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中的代码
//定位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*5Bdocument.getElementById("Latitude").innerHTML="latitude:"+latitude;document.getElementById("Longitude").innerHTML="longitude:"+longitude;document.getElementById("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文件,理出所有需要在离线状态下使用的资源
例如
CACHE MANIFEST #这是注释images/sound-icon.pngimages/background.pngclock.html clock.css clock.js NETWORK: test.cgiCACHE: style/default.cssFALLBACK: /files/projects /projects?
在html标签中声明 <html manifest="clock.manifest">?
HTML5离线应用更新缓存机制
分为手动更新和自动更新2种
自动更新:
在cache manifest文件本身发生变化时更新缓存 资源文件发生变化不会触发更新
手动更新:
使用window.applicationCache
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {window.applicationCache.update();}
在线状态检测
HTML5 提供了两种检测是否在线的方式:navigator.online(true/false) 和 online/offline事件。
在Android中构建离线应用
//开启应用程序缓存webSettingssetAppCacheEnabled(true);String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();//设置应用缓存的路径webSettings.setAppCachePath(dir);//设置缓存的模式webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//设置应用缓存的最大尺寸webSettings.setAppCacheMaxSize(1024*1024*8);//扩充缓存的容量public void onReachedMaxAppCacheSize(long spaceNeeded,long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {quotaUpdater.updateQuota(spaceNeeded * 2);}?
(完)还有一个尾巴关于canvas绘图的 不如之前记录的来的详细 就不做介绍了
?