How to save WebView state and restore it in Android Lollipop?

后端 未结 2 1705
没有蜡笔的小新
没有蜡笔的小新 2021-01-15 05:28

This question is asked multiple times and it has answers that used to work. Recently in documentation said, they have removed this feature for security reasons. Only some li

相关标签:
2条回答
  • 2021-01-15 05:43

    Setting android:configChanges="orientation|screenSize" for Activity in Manifest for retaining the state of activity that has Webview in it, if there is no difference in layout for portrait and landscape view.

    You can save Webview state as:

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

    and reload only if saved state is not null like:

    if (savedInstanceState == null) {
        webView.loadUrl("replace_with_your_url")
    }
    
    0 讨论(0)
  • 2021-01-15 05:51

    Finally I figured out the solution. There is no way to save the state of WebView and have all of the content, so we need to prevent reloading or recreating the webView. In order to have one instance of our activity that contains webView we should add the following code to our Manifest file:

    <activity ...
            android:launchMode="singleInstance"
            android:alwaysRetainTaskState="true">
    

    Then if through your application you needed to recreate the instance entirely to refresh the webView, you can use finish(); if it's inside of the activity or if you are in another activity and you want to recreate your webView activity, read this link to do it.

    0 讨论(0)
提交回复
热议问题