gpt4 book ai didi

java - webview离线时隐藏或替换 "webpage not available"

转载 作者:行者123 更新时间:2023-12-01 13:57:27 26 4
gpt4 key购买 nike

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;


public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView)findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl(" my site ");
webView.setWebViewClient(new WebViewClient(){});


}
}
<小时/>

如何隐藏或替换网页不可用页面?(请让我知道在哪里放置代码来隐藏或替换它)

谢谢

最佳答案

在加载到WebView之前,您可以检查是否有任何连接(Wi-Fi或3G)。

创建一个Utility类(比如AppUtility.java)编写这个方法

/**
* Determine connectivity. a utility method to determine internet
* connectivity this is invoked before every web request
*
* @param ctx
* the ctx
* @return true, if successful
*/
public static boolean determineConnectivity(Context ctx) {
ConnectivityManager manager = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
return info != null && info.getState() == NetworkInfo.State.CONNECTED;
}

现在在 WebView 中加载页面之前检查连接

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView)findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient(){});

if(AppUtility.determineConnectivity())
webView.loadUrl(" my site ");
else
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();

}
}

希望这会有所帮助。

关于java - webview离线时隐藏或替换 "webpage not available",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19554869/

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