Issue
I'm making an Android app that's a complex javascript app embedded in a web view. The web view refreshes every time the main activity's destroyed (ie due to rotation, back button press, etc).
To preserve the state of the web page, I to override onSaveInstanceState
and onRestoreInstanceState
:
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
// Save the state of the WebView
webView.saveState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
// Restore the state of the WebView
webView.restoreState(savedInstanceState);
}
This prevented a refresh, but fell short of preserving the display state of the web page, which is important for me since the user loses work in my complex js app stored in the display state.
I then tried to manually handle configuration changes by overriding onConfigurationChanged
. This method preserved state for rotation and other config changes, but display state was all lost when the user pressed the Android back button (which destroys the activity).
I'm now considering storing the web view on a fragment that's preserved in the bundle for onCreate, but I'm not sure if that preserves the display state.
I'm also considering overriding onDestroy to query the javascript in the web view for the current app state (say in some Blob or json format) and then store that in the bundle (or even in a local SQLite blob), but I can't find a synchronous method for polling javascript state in Android. I could send a java object into the javascript that maintains the state of the app with Android's addJavascriptInterface method, but computing the state of the web app requires a lot of work - I don't want to periodically poll for the state with a timer in the web app.
Any ideas on how to preserve the display state (as in any DOM elements dynamically created or text input) of a web view across activity destruction? Or how to remember the display state for later re-construction?
I feel that this is a roadblock for developers who basically want to make Android apps powered centrally by javascript embedded in a web view.
Solution
You just need to treat your code inside WebView as a web application, and use storage features provided by HTML. Make sure to enable them via WebSettings though (use this and this setting). Alternatively, use similar functionality exposed via an injected Java object, this way you can easily modify stored data in your Java code.
State of DOM and JS is in fact quite complex, and may involve network connections (via XHR and WebSockets), so trying to save it as a dump is a losing effort.
Answered By - Mikhail Naganov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.