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

梦想的初衷 提交于 2019-12-30 11:32:34

问题


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 limited things can be restored for the webView state. I have tried multiple ways to do it but every time it refreshes the webView state and it doesn't show the webView content.

What I want to do?

I have a web app that I want to retrieve the user content after time-out (If they input their credentials correct).



What I have done so far?

1- I have tried all solutions including the following approaches:

@Override
protected void onSaveInstanceState(Bundle outState) {
    webView.saveState(outState);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.blah);
   WebView webview = (WebView)findViewById(R.id.webview);
   if (savedInstanceState != null)
      webview.restoreState(savedInstanceState);
   else
      webview.loadUrl(URLData)
}

Also manifest file

android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|uiMode|screenSize|smallestScreenSize"

2- I tried to show my Time-Out activity as a dialog and it worked if I just dismiss it without evaluating the credentials but if I evaluate and dismiss the dialog it recreates the webView.

Any help would be appreciated.


回答1:


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.



来源:https://stackoverflow.com/questions/28096779/how-to-save-webview-state-and-restore-it-in-android-lollipop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!