gpt4 book ai didi

android - 如何为 WebView 编辑或创建自定义错误页面?

转载 作者:IT老高 更新时间:2023-10-28 23:20:48 24 4
gpt4 key购买 nike

我创建了一个 WebView 布局,用于访问特定网站,但是当手机不可用时,编辑或创建自定义“网页不可用”资源会很有用有网络连接或页面超时。我知道这是可能的,因为如果您在手机处于飞行模式时打开应用程序“Wikidroid”,您会收到“Article not available”错误页面而不是标准的 Android “Web page not available”错误页面。

我在互联网上到处搜索,但没有找到任何在线资源来解决这个请求。非常感谢任何和所有帮助。提前致谢。

最佳答案

要确定设备何时有网络连接,请请求权限 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />然后您可以使用以下代码进行检查。首先将这些变量定义为类变量。

private Context c;
private boolean isConnected = true;

在您的onCreate()方法初始化 c = this;

然后检查连接。

ConnectivityManager connectivityManager = (ConnectivityManager)
c.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni.getState() != NetworkInfo.State.CONNECTED) {
// record the fact that there is not connection
isConnected = false;
}
}

然后拦截WebView requets,您可以执行以下操作。如果您使用它,您可能希望自定义错误消息以包含onReceivedError 中可用的一些信息。方法。

final String offlineMessageHtml = "DEFINE THIS";
final String timeoutMessageHtml = "DEFINE THIS";

WebView browser = (WebView) findViewById(R.id.webview);
browser.setNetworkAvailable(isConnected);
browser.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isConnected) {
// return false to let the WebView handle the URL
return false;
} else {
// show the proper "not connected" message
view.loadData(offlineMessageHtml, "text/html", "utf-8");
// return true if the host application wants to leave the current
// WebView and handle the url itself
return true;
}
}
@Override
public void onReceivedError (WebView view, int errorCode,
String description, String failingUrl) {
if (errorCode == ERROR_TIMEOUT) {
view.stopLoading(); // may not be needed
view.loadData(timeoutMessageHtml, "text/html", "utf-8");
}
}
});

关于android - 如何为 WebView 编辑或创建自定义错误页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4101331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com