I've develop an Android app with phonegap, my app need to swicthing on the toggle button, then user can close the app and running it in background service. My problem is when I close the app and back to the app again, its back to the initial state with toggle button off. So, My question is how can we saving/restroring app state on android and phonegap?
I've read this Save & restoring WebView in an embedded PhoneGap app , but I still don't understand about restoreFromPreferences() and saveToPreferences(out) Can anyone help?
*Sorry for bad english
As @geet said, localStorage is what you need to store datas and retrieve them later. According to Phonegap website, localstorage provides access to a W3C Storage interface. You can read about it here : http://dev.w3.org/html5/webstorage/#the-localstorage-attribute.
To save a toggle button position this is what I do :
<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>
Make sure in your HTML that your toggle element (form me a checkbox) isn't checked by default :
<input type="checkbox" name="onoffswitch" id="onoffswitch">
About Pause and Resume, you can perform actions when these events are called. To do this :
<script>
document.addEventListener("resume", yourCallbackFunction, false);
document.addEventListener("pause", yourCallbackFunction, false);
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With