在Phonegap上恢复应用程序状态

3
我使用phonegap开发了一个Android应用,我的应用需要通过切换开关按钮来关闭应用并在后台服务中运行。我的问题是,当我关闭应用并再次打开应用时,应用会回到最初的状态,即开关按钮关闭。那么我的问题是,我们如何在Android和phonegap上保存/恢复应用程序状态?
我阅读了这个 Save & restoring WebView in an embedded PhoneGap app ,但我仍然不理解restoreFromPreferences()saveToPreferences(out)。有人可以帮忙吗?
*抱歉我的英语不好。
3个回答

5

正如 @geet 所说,localStorage 是您需要存储数据并稍后检索它们的方法。

根据 Phonegap 网站,localstorage 提供对 W3C 存储接口的访问。您可以在此处阅读相关信息:http://dev.w3.org/html5/webstorage/#the-localstorage-attribute

要保存切换按钮位置,这是我的方法:

<script>

function onDeviceReady() {

// Set togglebutton to false default
var togglebutton = window.localStorage.getItem("togglebutton");
if (togglebutton==null) window.localStorage.setItem("togglebutton", 'false');

// Set default state
if (window.localStorage.getItem("togglebutton")=='true') {
    $('#onoffswitch').attr("checked", "checked");
}

// Switch onoffswitch event
$('#onoffswitch').on('change', function(){
    if ($(this).prop('checked')) {
        window.localStorage.setItem("togglebutton", 'true');
    } else {
        window.localStorage.setItem("togglebutton", 'false');
    }
});

}

</script>

确保在你的HTML中,你的切换元素(例如复选框)不是默认勾选状态:

<input type="checkbox" name="onoffswitch" id="onoffswitch">

关于暂停和恢复,您可以在调用这些事件时执行操作。要执行此操作,请按以下步骤:
<script>
    document.addEventListener("resume", yourCallbackFunction, false);
    document.addEventListener("pause", yourCallbackFunction, false);
</script>

我明白了,所以如果我有很多东西要处理,我必须一个一个地存储到存储器中吗? - ikazxc56
如果您只需要存储一些值,localStorage是您的好朋友。否则,请查看SQlite Phonegap数据库http://docs.phonegap.com/fr/1.2.0/phonegap_storage_storage.md.html - David

1
您可以在JS中的localstorage中存储任何数据。

e.g

保存var username的值。

localStorage.setItem("username",edited_name);

检索

var getUser=localStorage.getItem("username");

希望它对您有所帮助!

你能解释一下怎么做吗?是在Phonegap上使用暂停和恢复事件吗? - ikazxc56
你应该知道它会将所有值转换为字符串,然后存储为字符串。 - celwell

0
function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
    document.addEventListener("pause", onPause, false);

function onDeviceReady() {
 
    var pageNow = document.getElementsByTagName(body);
    var currentPage = JSON.stringify(pageNow);
    localStorage.setItem("uiState", currentPage);

}

function onPause() {
//retrieve info here

var pageShow = document.getElementsByTagName(body);

let techStack = localStorage.getItem("uiState");
// JSON.parse(techStack); //unnecessary because the parser will detect HTML
pageShow.innerHTML(techStack);

}
}

你可以使用不同的选择器获取任何元素中UI的当前状态。

稍后将更新此答案以包含SQL。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接