Android 长时间休眠后 webview 无响应

Android webview unresponsive after long sleep

我正在开发一个业余爱好应用程序。它在主布局中使用 webview。单击 webview 内的链接会使用户保持在 webview 内。启动后一切正常,但仍在应用程序内。但是,在 phone 休眠一段时间后,我重新打开应用程序以从我离开的地方开始冲浪,我注意到一些意外行为。

  1. 该网页加载文本但不加载图像(问号或空白 space 图像应位于的位置)。
  2. 在 webview 中单击网页内的链接会使用户离开 webview 并尝试打开外部浏览器。

作为参考,我已经做了:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    webview.saveState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    webview.restoreState(savedInstanceState);
}

以及 onCreate 代码中的这个:

if (savedInstanceState != null) {
    webview.restoreState(savedInstanceState);
}else{
    // this means my app is starting from scratch and do the necessary webview loading
}

我不确定我错过了什么,但 webview 似乎,呃,"broken",因为没有更好的术语,经过长时间的睡眠。我尝试搜索有关此的更多信息,但没有看到更多人遇到此问题。要么人们不希望以这种方式使用 webview,要么我做错了什么。我认为是后者。

感谢任何反馈。

更多信息: webview 是应用程序的根 activity。复制问题的步骤只是在 webview 中按主菜单,因此应用程序在 webview activity 中暂停,等待或让 phone 睡眠,打开 phone,打开应用程序和 activity 在 webview 加载的最后一页重新启动。等待足够长的时间,网络视图 activity 将表现出上述行为。

我还设置了基本的生命周期函数 onResume、onPause、onStop、onDestroy 都调用它们各自的超级函数等。

我也使用 WebViewClient 和 WebChromeClient。

我的 WebViewClient 只负责 "onPageStarted"、"onReceivedError"、"shouldOverloadUrlLoading" 和 "onPageFinished"。

另一方面,我的 WebChromeClient 只执行 "onGeolocationPermissionShowPrompt" 和 "onProgressChanged"。

两者都用于在 webview 顶部创建加载栏以显示页面加载进度。

所以,我已经做了很多测试,但最有用的是每个生命周期 onResume、onPause、onStop、onDestroy 以及 onSaveInstanceState 和 onRestoreInstanceState 中的 Toast 消息。

我正在使用这样的代码块(恢复状态)[重写上面的代码]:

if(savedInstanceState!=null){
    webview.restoreState(savedInstanceState);
}else{
    // do the webview getsettings such as setUseWideViewPort and setSupportZoom
    // setInitialScale, setJavaScriptEnabled, etc..
    // as well as setting WebViewClient and WebChromeClient
    // then preloading the webview with the default url
}

由于内部用于调试的 Toast 消息,我注意到在长时间睡眠后,Android 显然杀死了我的 activity 并再次调用了 onCreate。我没有考虑到的是 webview.restoreState 没有恢复关于 webview 的所有内容。

它不会恢复上面 "else" 块内的任何内容。实际上,在此期间设置的任何内容都会消失。因此,只有网站被保存,WebView和WebChrome客户端的none被保存了。

这导致了上述行为。

通过将设置块从 "else" 块移到它外面,我的 webview 能够使用必要的设置再次进行自我设置。

补充信息:我还删除了 onRestoreInstanceState() 受保护函数,因为它似乎没有做任何我关心的事情。

如果我忽略了解决方案中的任何内容,仍然欢迎提出意见和建议。谢谢。