I have an app that allows users to play games online or cache them locally. When they convert their game to cached, I don't want them to lose progress.
Prior to KitKat, you could set the localstorage dir, but I need newer phones to support this feature.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
playingField.getSettings().setDatabasePath("/data/data/" + playingField.getContext().getPackageName() + "/databases/");
}
I can't find a replacement method. As a result, here are the two directories:
root@ghost:/data/data/com.myapp.android/app_webview/Local Storage #
ls -la
total 80
drwx------ 2 u0_a165 u0_a165 4096 2017-01-06 11:51 .
drwxrwx--x 4 u0_a165 u0_a165 4096 2017-01-06 11:41 ..
-rw------- 1 u0_a165 u0_a165 4096 2017-01-06 11:51 file__0.localstorage
-rw------- 1 u0_a165 u0_a165 0 2017-01-06 11:51 file__0.localstorage-journal
-rw------- 1 u0_a165 u0_a165 4096 2017-01-06 12:02 http_cdn.myapp.com_0.localstorage
-rw------- 1 u0_a165 u0_a165 0 2017-01-06 12:02 http_cdn.myapp.com_0.localstorage-journal
Has anyone solved this issue?
I may try synchronizing the files during the onPause() of the activity, but I would like to know if there is a more elegant solution - like consolidated storage.
This feels a bit dirty, but it works (on
KitKatand newer)!The
LocalStorageCopierclass below uses aSharedPreferencesstore to keep track of the items (feel free to use whatever else you want instead). Before you load the url (local or remote) create an instance of theLocalStorageCopierand add it as aJavascriptInterfaceto your webView:Note: it is important that the javascript interface is added before loading the page. I was scratching my head as to why "backup is undefined" until I moved this bit to before loading the url (I was adding it just prior to performing the backup).
Now you just have to tie in the backup and restore actions.
Backup: As you mentioned above, the
onPausemethod is a good place to back this stuff up. At an appropriate place within youronPauseadd the code below:where
BACKUP_JAVASCRIPTis"(function() { console.log('backing up'); backup.clear(); for (var key in localStorage) { backup.set(key, localStorage.getItem(key)); }})()"So now every time your activity is paused, your
localStorageis backed up.Restore is done in a very similar fashion. You need to initiate the restore action after the page is loaded. This is where the
WebClientclass (code below) comes in. Once the page is done loading, you have to grab all the items in yourLocalStorageCopierinstance and put them in thelocalStorage. The javascript forRESTORE_JAVASCRIPTis:"(function(){console.log('Restoring'); backup.dump(); var len = backup.size(); for (i = 0; i < len; i++) { var key = backup.key(i); console.log(key); localStorage.setItem(key, backup.get(key));}})()"LocalStorageCopier
WebClient