Does WebView saveState() preserve Javascript variables/environment?

我与影子孤独终老i 提交于 2019-11-30 05:20:43
diyism

Very few information found, only this line:

Please note that this method no longer stores the display data for this WebView. The previous behavior could potentially leak files if restoreState(Bundle) was never called.

and this line:

Returns the same copy of the back/forward list used to save the state.

in the javadoc for WebView.saveState(Bundle).

Ryan Schultz

As user2113581 commented, moving the WebView into a context of the application rather than the Activity is a potential solution. This still has all of the pitfalls that user2113581 mentioned, including <select> not working (because it creates a window, but an application context does not have a window token).

I have extended my Application to manage my webview...

MyApplication.java:

public class MyApplication extends Application {
  private WebView mWebView;
  private boolean mWebViewInitialized;
  // ...

  @Override public void onCreate() {
    super.onCreate();
    mWebView = new WebView(this);
    mWebViewInitialized = false; // we do some initialization once in our activity.
  }

  public WebView getWebView() { return mWebView; }
  public boolean isWebViewInitialized() { return mWebViewInitialized; }
  public void setWebViewInitialized(boolean initialized) {
    mWebViewInitialized = initialized;
  }
}

In our activity:

@Override protected void onCreate(Bundle savedInstanceState) {
  // ...
  MyApplication app = (MyApplication) getApplication();
  mWebView = app.getWebView();
  if (!app.isWebViewInitialized()) { 
    /* first time initialization */ 
    app.setWebViewInitialized(true);
  }
}

Finally, in your Activity, you will want to add the mWebView to a container view (FrameLayout, or similar) during a lifecycle event that makes sense. You'll need to remove it from the container when the activity is being paused or stopped. I've used onResume and onPause with good results.

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