我如何覆盖页面未找到net::ERR_ADDRESS_UNREACHABLE在Android Studio Kotlin



我只是不希望用户在我的电视应用程序看到我使用的URL,当网页是不可达的应用程序。在这种情况下,他们将得到一个错误消息,URL为:

"无法加载http://example.com/action.php的网页,因为:net::ERR_ADDRESS_UNREACHABLE"我试图重写fun onReceivedError,如下所示:

public class MyWebViewClient(activity: MainActivity) : WebViewClient() {
private val activity = activity
@SuppressWarnings("deprecation")
override  fun  onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
//super.onReceivedError(view, errorCode, "No internet!", "failingUrl") //Here I supressed super.
Toast.makeText(activity, "onReceivedError! errorCode=$errorCode description: $description url: $failingUrl", Toast.LENGTH_LONG).show()
} 

}

Toast显示出来了,但是仍然显示错误消息,所以我猜还有一些其他的函数需要重写。我用的是AVD (55"Android TV (1080p)与API 22 (Android 5.1)

我在这里错过了什么?请告知,谢谢。

由于我不知道的原因,如果你不以特定的方式覆盖该函数,即提供一个替代的错误HTML页面,默认的android错误页面将不断弹出。我是在找到一个类似问题的答案后得出这个结论的:在这里输入链接描述

所以我的Kotlin代码现在看起来像这样:
val wedData: String =  "<html><body><h1>No Internet!</h1></body></html>"
val mimeType: String = "text/html"
val utfType: String = "UTF-8"        
var mWebView : WebView
mWebView = findViewById(R.id.web_view)
mWebView.setWebViewClient(object : WebViewClient() {
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
// mWebView.loadUrl("file:///android_asset/myerrorpage.html")
mWebView.loadData(wedData,mimeType,utfType)
}
}) 
mWebView.apply {

var postData = "user=" + URLEncoder.encode("user", "UTF-8") + "&mode="+URLEncoder.encode("client", "UTF-8")
settings.javaScriptEnabled = true            
settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
postUrl("http://example.com/", postData.encodeToByteArray())
}

最新更新