切换时保存 WebView 状态 Activity

Save State of WebView when switching Activity

我正在制作一个 Web 浏览器,其中包含一些带有 WebView 的活动。假设我在 activity A 中,当我切换到 activity B 并在那里浏览一些内容然后返回到 activity A 时,默认的 URL 是打开的。我需要一个具体的解决方案来将我的状态保存在 Bundle 中。

@Override
   protected void onResume() {
      super.onResume();

      Toast.makeText(getBaseContext(), "OnResume activity called",Toast.LENGTH_LONG).show();

      if(webView_bundle!=null)
      {
          wv.restoreState(webView_bundle);
      }

   }
@Override
   protected void onPause() {
      super.onStart();

      Toast.makeText(getBaseContext(), "OnPause activity called",Toast.LENGTH_LONG).show();
          wv.saveState(webView_bundle);

   }
@Override
protected void onSaveInstanceState(Bundle outState) {
    webView_bundle=(Bundle) outState.clone();
    wv.saveState(webView_bundle);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    webView_bundle=(Bundle) savedInstanceState.clone();
    wv.restoreState(webView_bundle);
}

顺便说一句,我没有使用Fragments而是使用API 19,即使切换到另一个activity,我应该如何保存activity的WebView的状态] 然后回到这个 activity?

WebView 未正确恢复其状态。这不是错误。这是一项旨在提升用户浏览活动隐私性的更改。来自 WebView documentation:

The standard behavior for an Activity is to be destroyed and recreated when the device orientation or any other configuration changes. This will cause the WebView to reload the current page. If you don't want that, you can set your Activity to handle the orientation and keyboardHidden changes, and then just leave the WebView alone. It'll automatically re-orient itself as appropriate.

维护状态的唯一方法是自己处理配置更改。或者,您可以避免完全使用标准 WebView,而选择像 Crosswalk 这样的自定义 WebView。

启用以下属性,除了上面的代码外,还很有魅力:)

android:launchMode="singleInstance"
android:alwaysRetainTaskState="true"

对于 AndroidManifest.xml 中包含 WebView 的每个 activity 都对我有用:)