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
lifecycle event to look at the current URL and save it to SharedPreferences
:
1
2
3
4
5
6
7
8
9
10
11
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
when the activity gets created:
1
2
3
4
5
6
7
8
9
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