【问题标题】:Android webview unresponsive after long sleep长时间睡眠后Android webview无响应
【发布时间】:2016-06-28 05:01:33
【问题描述】:

我正在开发一个小爱好应用程序。它在主布局中使用 webview。单击 webview 内的链接使用户保持在 webview 中。启动后一切都很好,但仍在应用程序中。但是,在手机休眠一段时间后,我重新打开应用程序以从上次中断的地方进行冲浪,我注意到一些意外行为。

  1. 网页加载文本但不加载图像(问号或只是图像预期的空白区域)。
  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 似乎,呃,“坏了”,因为缺乏更好的术语,经过长时间的睡眠。我已尝试搜索有关此问题的更多信息,但没有看到更多人遇到此问题。要么人们不希望以这种方式使用 webview,要么我做错了什么。我认为是后者。

感谢您的任何反馈。

更多信息: webview 是应用程序的根活动。复制问题的步骤只是在 webview 中按下主菜单,以便应用程序在 webview 活动中暂停、等待或让手机休眠、打开手机、打开应用程序,然后活动在 webview 加载的最后一页重新启动。等待足够长的时间,webview 活动将表现出上述行为。

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

我也使用 WebViewClient 和 WebChromeClient。

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

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

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

【问题讨论】:

    标签: android webview android-lifecycle


    【解决方案1】:

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

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

    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 显然会杀死我的活动并再次调用 onCreate。我没有考虑的是 webview.restoreState 没有恢复有关 webview 的所有内容。

    它不会恢复上面“else”块中的任何内容。实际上,在那段时间设置的任何东西都会消失。因此,只保存了网站,没有保存 WebView 和 WebChrome 客户端。

    这导致了上述行为。

    通过将 setup 块从“else”块移到它之外,我的 webview 能够使用必要的设置再次设置自己。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-08
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多