确定互联网连接的更好的方式 [英] The Better Way of Determining Internet Connectivity

查看:99
本文介绍了确定互联网连接的更好的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初一个问题,为什么一个web观点,当一个BroadcastReceiver说,该设备已连接到互联网故障:<一href="http://stackoverflow.com/questions/16245827/webview-fails-w-good-connection/16245956#16245956">WebView失败W /连接良好

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

这导致了两个答案,一个技术上是正确的和解决方法。然而,无论是完美的。我的问题是:什么是确定有效Internt的连接的更好的办法

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;
       }
    }
 }

感谢您的帮助提前

Thanks for the help in advance

推荐答案

在我们使用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通我们的服务器,只是为了看看,如果我们可以打他们。没关系,如果我们能打到在网络上gajillion网站,只要我们能打出我们的,所以我们做我们的第一个简短的电话,如果失败,我们说无法连接到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"

这篇关于确定互联网连接的更好的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆