我有一个Android应用程序,它有一个webview。当没有互联网连接时,webview将显示页面不可用。我希望尽可能让它看起来像一个应用程序,所以我不想显示这个页面。我在网上找到了一些有用的信息,教你如何隐藏或加载其他内容来覆盖它,但我真正想要的是留在当前页面和一个小弹出对话框说没有连接。基本上,当用户点击webview中的任何内容时,首先检查连接。如果没有连接,请留在原处并弹出一个对话框。
感谢您的帮助!!
编辑:
就像我说的,我已经知道如何从在线样本中检查互联网连接。我的问题是我不知道如何停止加载下一页。需要说明的是,当用户尝试转到下一页时,请检查是否存在互联网连接。如果没有连接,页面将保持原样,不会进入下一页。我希望用户能够看到他们上次加载的页面,并在网页内容仍然存在时获得通知。谢谢!
答案 0 :(得分:31)
我在我的项目中使用了以下内容:
DetectConnection.Java
import android.content.Context;
import android.net.ConnectivityManager;
public class DetectConnection {
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected());
}
}
主要代码:
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
wv = (WebView) findViewById(R.id.donate_webView1);
c = new CustomWebViewClient();
wv.setWebViewClient(c);
wv.clearCache(true);
wv.clearHistory();
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.loadUrl("http://www.google.com");
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
}
更新清单:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:5)
您可以使用我的CustomWebViewClient
-
您需要做的就是将其附加到您的webView
webView.setWebViewClient(new CustomWebViewClient());
CustomWebViewClient类
/**
* WebViewClient subclass loads all hyperlinks in the existing WebView
*/
public class CustomWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When user clicks a hyperlink, load in the existing WebView
view.loadUrl(url);
return true;
}
Dialog loadingDialog = new Dialog(WebViewActivity.this);
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webViewPreviousState = PAGE_STARTED;
if (loadingDialog == null || !loadingDialog.isShowing())
loadingDialog = ProgressDialog.show(WebViewActivity.this, "",
"Loading Please Wait", true, true,
new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// do something
}
});
loadingDialog.setCancelable(false);
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request,
WebResourceError error) {
if (isConnected()) {
final Snackbar snackBar = Snackbar.make(rootView, "onReceivedError : " + error.getDescription(), Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Reload", new View.OnClickListener() {
@Override
public void onClick(View view) {
webView.loadUrl("javascript:window.location.reload( true )");
}
});
snackBar.show();
} else {
final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Enable Data", new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
webView.loadUrl("javascript:window.location.reload( true )");
snackBar.dismiss();
}
});
snackBar.show();
}
super.onReceivedError(view, request, error);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceivedHttpError(WebView view,
WebResourceRequest request, WebResourceResponse errorResponse) {
if (isConnected()) {
final Snackbar snackBar = Snackbar.make(rootView, "HttpError : " + errorResponse.getReasonPhrase(), Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Reload", new View.OnClickListener() {
@Override
public void onClick(View view) {
webView.loadUrl("javascript:window.location.reload( true )");
}
});
snackBar.show();
} else {
final Snackbar snackBar = Snackbar.make(rootView, "No Internet Connection ", Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Enable Data", new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(Settings.ACTION_WIRELESS_SETTINGS), 0);
webView.loadUrl("javascript:window.location.reload( true )");
snackBar.dismiss();
}
});
snackBar.show();
}
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public void onPageFinished(WebView view, String url) {
if (webViewPreviousState == PAGE_STARTED) {
if (null != loadingDialog) {
loadingDialog.dismiss();
loadingDialog = null;
}
}
}
}
检查连接方法
/**
* Check if there is any connectivity
*
* @return is Device Connected
*/
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null != cm) {
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
return false;
}
答案 2 :(得分:0)
您需要覆盖shouldOverrideUrlLoading的WebViewClient方法以捕获网址点击次数。
要检查Wifi状态,您需要使用ConnectivityManager
试试这个:
WebView mWebView;
NetworkInfo networkInfoWifi = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mWebView.setWebViewClient(mWebClient);
WebViewClient mWebClient = new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
return true;
}
@Override
public void onLoadResource(WebView view, String url){
if (networkInfoWifi.isConnected()) {
//Take action
}
}
}
我建议将您的问题分成两个较小的步骤 - 单击拦截和连接状态检查,然后搜索它们。这产生了大量的结果,我能够使用这两个现有的答案来组合代码:
答案 3 :(得分:0)
webView.setWebViewClient(new WebViewClient() {
int errorCode = 0;
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return handleUri(view, url);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return handleUri(view, request.getUrl().toString());
}
private boolean handleUri(WebView view, final String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
if(errorCode == 0) {
//CHECK IS PAGE I NEED AND DO STUFF
} else {
errorCode = 0;
//delay and try again
}
}
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
handleError(errorCode);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
handleError(error.getErrorCode());
}
private void handleError(int errorCode) {
this.errorCode = errorCode;
}
});
答案 4 :(得分:0)
您可以通过以下代码检查设备是通过数据还是wifi连接到互联网
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = manager.getActiveNetworkInfo();
boolean hasConnect = (i!= null && i.isConnected() && i.isAvailable());
if(hasConnect)
{
// show the webview
}
else
{
// do what ever you need when when no internet connection
}
用户进入webview后,如果连接丢失,您可以从以下代码中捕获该事件
webView.setWebViewClient(new Callback());
public class Callback extends WebViewClient{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getApplicationContext(), "Failed loading app!, No Internet Connection found.", Toast.LENGTH_SHORT).show();
}
}
以下权限需要提供
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />