The Better Way of Determining Internet Connectivity(确定互联网连接的更好方法)
问题描述
最初是一个关于为什么广播接收器说设备已连接到互联网时网络视图失败的问题:WebView 因连接良好而失败
Originally a question about why a web view was failing when a broadcastReceiver said the device was connected to the internet: WebView Fails w/ Good Connection
这导致两个答案,一个技术上正确的和一个解决方法.然而,两者都不是完美的.我的问题是:确定有效互联网连接的更好方法是什么?
This lead to two answers, a technically correct and a workaround. However, neither is perfect. My question is: What is the better way of determining a valid internt connect?
(1)
public static boolean isConnectedToInternet()
{
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = false;
if(activeNetwork != null &&
activeNetwork.isConnected())
{
isConnected = true;
}
return isConnected;
}
//WebViewClient override
public void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
Log.e("web view error: "+errorCode, description);
if(errorCode == -6 &&
isConnectedToInternet())
{
view.reload();
}
else
{
view.loadUrl("");
}
}
(2)
public class MainActivity extends Activity {
boolean mConnected = false;
String mURL = "http://www.google.com";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VerifyInternetConnectionTask task = new VerifyInternetConnectionTask();
try {
mConnected = task.execute(mURL).get();
} catch (InterruptedException e) {
Log.e(TAG, "AsyncTask Interrupted Exception", e);
} catch (ExecutionException e) {
Log.e(TAG, "AsyncTask Execution Exception", e);
}
if (mConnected) {
Toast.makeText(this, "Connected to Internet", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Unable to connect to the Internet", Toast.LENGTH_LONG).show();
}
}
private class VerifyInternetConnectionTask extends AsyncTask<String, Void, Boolean> {
private static final String TAG = "VerifyInternetConnectionTask";
private boolean isNetworksAvailable() {
ConnectivityManager mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnMgr != null) {
NetworkInfo[] mNetInfo = mConnMgr.getAllNetworkInfo();
if (mNetInfo != null) {
for (int i = 0; i < mNetInfo.length; i++) {
if (mNetInfo[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
@Override
protected Boolean doInBackground(final String... params) {
final int CONNECTION_TIMEOUT = 2000;
if (isNetworksAvailable()) {
try {
HttpURLConnection mURLConnection = (HttpURLConnection) (new URL(params[0]).openConnection());
mURLConnection.setRequestProperty("User-Agent", "ConnectionTest");
mURLConnection.setRequestProperty("Connection", "close");
mURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
mURLConnection.setReadTimeout(CONNECTION_TIMEOUT);
mURLConnection.connect();
return (mURLConnection.getResponseCode() == 200);
} catch (IOException ioe) {
Log.e(TAG, "Exception occured while checking for Internet connection: ", ioe);
}
} else {
Log.e(TAG, "Not connected to WiFi/Mobile and no Internet available.");
}
return false;
}
}
}
提前感谢您的帮助
推荐答案
在我们使用 Web 服务的应用程序中,我们实际上采取了两步法.第一步将包括你的技术测试",看看我们是否在理论上启用了网络.如果失败,我们会发出警告消息,例如未检测到网络连接".
In our apps that use web services, we actually take a two step approach. The first step would include your "technical test" to just see if we are network enabled, in theory. If we fail that, we give a warning message like "No network connection detected".
我们要做的第二步是用最少的调用 ping 我们的服务器,看看我们是否可以访问它们.我们是否可以访问网络上的大量网站并不重要,只要我们可以访问我们的网站,所以我们会进行第一次快速调用,如果失败,我们会说无法连接到 siteX.请稍后再试"
The second step we do, is we ping our servers with a minimal call, just to see if we can hit them. It doesn't matter if we can hit a gajillion sites on the web, only if we can hit ours, so we do our first quick call, and if it fails, we say "Can't connect to siteX. Please try again later"
这篇关于确定互联网连接的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:确定互联网连接的更好方法


基础教程推荐
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01