我用 phonegap 开发了一个 Android 应用程序,我的应用程序需要在切换按钮上切换,然后用户可以关闭应用程序并在后台服务中运行它。我的问题是当我关闭应用程序并再次返回应用程序时,它返回初始状态并关闭切换按钮。 所以,我的问题是我们如何在 android 和 phonegap 上保存/恢复应用程序状态?
我读过这个Save & restoring WebView in an embedded PhoneGap app ,但我仍然不了解 restoreFromPreferences() 和 saveToPreferences(out) 谁能帮忙?
*抱歉英语不好
最佳答案
正如@geet 所说,localStorage 是您存储数据和稍后检索数据所需要的。 根据 Phonegap 网站,localstorage 提供对 W3C 存储接口(interface)的访问。您可以在这里阅读: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>
关于android - 在 Phonegap 上恢复应用程序状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17962090/