● 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:
- //清空storage
- localStorage.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 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.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*5B
- document.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.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
- 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繪圖的 不如之前記錄的來的詳細 就不做介紹了