Skip to content

Instantly share code, notes, and snippets.

@nanoxd
Created March 22, 2017 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanoxd/652ddb82966bae75e5054b4b865908ad to your computer and use it in GitHub Desktop.
Save nanoxd/652ddb82966bae75e5054b4b865908ad to your computer and use it in GitHub Desktop.
Save last url used in an Android Webview as well as handle back button presses
package com.pxelated.app
import android.app.Activity
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
class MainActivity : AppCompatActivity() {
companion object {
val LAST_URL = "lastUrl"
}
// Lazy load the webview with all of our configuration
val webview: WebView by lazy {
val webview = findViewById(R.id.webview) as WebView
webview.settings.javaScriptEnabled = true
webview.settings.domStorageEnabled = true
webview.setWebChromeClient(WebChromeClient())
webview.setWebViewClient(WebViewClient())
webview
}
val prefs: SharedPreferences by lazy {
applicationContext.getSharedPreferences(applicationContext.packageName, Activity.MODE_PRIVATE)
}
val lastOrMainUrl: String by lazy {
prefs.getString(MainActivity.LAST_URL, BuildConfig.URL)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webview.loadUrl(lastOrMainUrl)
}
override fun onPause() {
super.onPause()
// Save the last url visited for this user
prefs.edit()
.putString(MainActivity.LAST_URL, webview.url)
.commit() // .apply can also be used here _へ__(‾◡◝ )>
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
// Check if the key event was the Back button and if there's history
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack()
return true
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (exit the activity or go to previous activity)
return super.onKeyDown(keyCode, event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment