WebView失败,连接良好

时间:2013-04-26 21:55:45

标签: android webview connectivity

我有一个监视网络连接的BroadcastReceiver,而我正在尝试做的是在互联网连接可用时重新加载网页视图。

然而,当getActiveNetworkInfo()。isConnect()返回true,并且我重新加载url时,Web视图无法说:

web view error:(-6) The connection to the server was unsuccessful.

确定连接的方法是可行的:

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

提前感谢您的帮助

2 个答案:

答案 0 :(得分:2)

下面的代码应该可以帮助您了解如何根据您的需求实现它,以验证设备是否能够连接到Internet。

将所需权限添加到AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

MainActivity

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

}

答案 1 :(得分:0)

我不确定为什么它的行为与我不同,但找到了合适的解决方法:

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

我希望这有助于其他人