Ref: Cordova Plugin File
安裝方式請參考連結Android
Read
window.SaveData = null;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
readFile();
}
function readFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotReadFS, null);
}
function gotReadFS(fileSystem){
fileSystem.root.getFile("[FileName檔案名稱]", null, gotFileEntry, null);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, null);
}
function gotFile(file){
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var txt = evt.target.result;
window.SaveData = txt;
};
reader.readAsText(file);
}Write
function writeFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotWriteFS, fail);
}
function gotWriteFS(fileSystem) {
fileSystem.root.getFile("[FileName檔案名稱]", {create: true, exclusive: false}, gotFileEntryWrite, fail);
}
function gotFileEntryWrite(fileEntry){
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
var txt = "xxxxxxxxxxxxxxxxx";
writer.write(txt);
writer.onwriteend = function(evt){
<<寫檔完成後要做的事情>>
};
}iOS
程式與Android一樣,不需更改
應用
一進入頁面就馬上讀取檔案,並且將讀取到的值顯示在jQueryMobile的Component上。
範例:App開啟便立即讀取儲存在手機上的帳號資訊,並顯示在帳號、密碼的textbox中
注意!此種一開啟就要開始讀檔的程式必須要確定PhoneGap、jQueryMobile兩Framework皆載入完成後才能執行,否則很容易得到意料之外的效果。
window.PhonegapReady = false; //PhoneGap Framework載入完畢
window.JQMReady = false; //jQueryMobile Framework載入完畢
isReadFileReady("ReadLoginInfo"); //讀檔
isBindLoginReady("BindLoginInfo"); //顯示內容至jQueryMobile的元件上
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
window.PhonegapReady = true;
}
$(document).one("pagebeforeshow", function(){
window.JQMReady = true;
});
function isReadFileReady(action) {
if (window.PhonegapReady == true && window.JQMReady == true && (window.SaveData == "" || window.SaveData == null)) {
if(action=="ReadLoginInfo") {
readFile(); //讀檔
}
}
else {
window.setTimeout("isReadFileReady(\"" + action + "\");",200);
}
}
function isBindLoginReady(action) {
if (window.PhonegapReady == true && window.JQMReady == true && window.SaveData != "" && window.SaveData != null) {
if(action=="BindLoginInfo") {
bindContent(); //將讀取到的檔案內容更新至jQM元件中
}
}
else {
window.setTimeout("isBindLoginReady(\"" + action + "\");",100);
}
}
沒有留言:
張貼留言