Sid*_* 6x 17 android android-webview
我创建了一个WebView布局,用于访问特定网站,但是当手机没有网络连接或页面超时时,编辑或创建自定义" 网页不可用 "资源会很有用.我知道这是可能的,因为如果您在手机处于飞行模式时打开应用程序" Wikidroid ",则会收到" 文章不可用 "错误页面而不是标准Android" 网页不可用 "错误页面.
我在互联网上搜索高低,并没有提出任何解决此请求的在线资源.任何和所有的帮助非常感谢.提前致谢.
Bri*_*ian 20
要确定设备何时具有网络连接,请请求权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />,然后您可以使用以下代码进行检查.首先将这些变量定义为类变量.
private Context c;
private boolean isConnected = true;
Run Code Online (Sandbox Code Playgroud)
在你的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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后拦截WebViewrequets,你可以做类似以下的事情.如果使用此方法,则可能需要自定义错误消息以包含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");
}
}
});
Run Code Online (Sandbox Code Playgroud)
小智 10
Marco W.是对的.
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
myWebView.loadUrl("file:///android_asset/custom_url_error.htm");
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27237 次 |
| 最近记录: |