Search code examples
androidkotlinandroid-webview

WebView resets when app is launched from launcher


I load a web page in a WebView. The state of the page changes via JavaScript. If I put the app in the background, and then return to it using the task switcher, the state of the web page is preserved. If I send it to background and then open it from the launcher, the web page is reset. What can I do to preserve its state when launched from the launcher?

class MainActivity : Activity() {
    private var webView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_main)

        webView = findViewById(R.id.webView)
        webView?.webViewClient = OzvenaWebViewClient(this)
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
        webView?.settings?.javaScriptEnabled = true
        if (savedInstanceState != null)
            webView?.restoreState(savedInstanceState)
        else
            webView?.loadUrl("https://markonius.gitlab.io/ozvena/ozvena.html")
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        webView?.saveState(outState)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        webView?.restoreState(savedInstanceState)
    }

    override fun onBackPressed() {
        moveTaskToBack(true)
    }
}

EDIT: I overrode the wrong onSaveInstanceState, I fixed it now. One issue I can see now is that savedInstanceState in onCreate is always null, even after onSaveInstanceState is invoked.


Solution

  • Try adding android:launchMode="singleTask" to your AndroidManifest.xml

    <activity android:name=".activity.MainActivity"
                android:launchMode="singleTask"
                />