1

最初是一个关于为什么当广播接收器说设备连​​接到互联网时 Web 视图失败的问题:WebView Fails w/ Good Connection

这导致两个答案,一个技术上正确的和一个解决方法。然而,两者都不是完美的。我的问题是:确定有效互联网连接的更好方法是什么?

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

我在这里先向您的帮助表示感谢

4

1 回答 1

0

在我们使用 Web 服务的应用程序中,我们实际上采用了两步方法。第一步将包括你的“技术测试”,看看我们是否在理论上启用了网络。如果我们失败了,我们会给出一个警告信息,比如“没有检测到网络连接”。

我们要做的第二步是用最少的调用 ping 我们的服务器,看看我们是否可以访问它们。我们是否可以访问网络上的大量网站并不重要,只要我们可以访问我们的网站,所以我们会进行第一次快速调用,如果失败,我们会说“无法连接到 siteX。请稍后再试"

于 2013-04-27T22:57:30.803 回答