Persisting the Last Visited URL in an Android WebView
I had a problem in Android where I wanted the user to resume their WebView session and pick up where they left off. I also didn’t want to use WebView.saveState or WebView.restoreState due to the side effects that could happen. The example code below uses Kotlin.
#Saving the current URL
We can hook into the onPause{:kotlin} lifecycle event to look at the current URL and save it to SharedPreferences{:kotlin}:
val prefs: SharedPreferences by lazy {
applicationContext.getSharedPreferences(applicationContext.packageName, Activity.MODE_PRIVATE)
}
override fun onPause() {
super.onPause()
val edit = prefs.edit()
edit.putString("lastUrl", webView.url)
edit.commit() // You could also use `.apply` here _へ__(‾◡◝ )>
}#Loading the URL
To retrieve the value, we can pull it out from SharedPreferences{:kotlin} when the activity gets created:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Pull saved URL out of SharedPreferences
val lastOrMainUrl = prefs.getString(lastUrl, BuildConfig.URL)
webview.loadUrl(lastOrMainUrl)
}#Example Code
You can find the full activity with some refactoring in this gist
No comments yet. Share on Mastodon and see your comment or write a post on your blog if you support Webmentions
No reposts yet. Share on Mastodon and see your repost or write a post on your blog if you support Webmentions
No likes yet. Share on Mastodon and see your like or write a post on your blog if you support Webmentions
No bookmarks yet. Share on Mastodon and see your bookmark or write a post on your blog if you support Webmentions
Powered by Webmentions