检查Internet连接是否可用?

时间:2011-11-05 05:37:03

标签: android

我正在开发在线应用。 [问题]当互联网停机或不可用时,它给我错误[强制关闭],我试图使用broadCast接收器处理但不满足精确解决方案,寻找更好的解决方案。

public class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

    NetworkInfo info = intent
            .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

    if (null != info) {

        String state = info.getState().toString();

        if (state.equalsIgnoreCase("CONNECTED")) {
            SplashScreen.isWiFiConnected = true;
            Log.i("isWifiConnected", "=================TRUE");
        } else {
            SplashScreen.isWiFiConnected = false;
            Log.i("isWifiConnected", "=================FALSE");
        }

    }

}

}

感谢。

3 个答案:

答案 0 :(得分:6)

static String data = null;
private static HttpPost httppost;
private static HttpParams httpParameters;
private static int timeoutConnection = 30000;
private static HttpClient httpclient = null;
private static HttpResponse response = null;
private static int responseCode=0;
public static ConnectivityManager mConnectivityManager;
public static NetworkInfo mNetworkInfo;
public static boolean isNetError=false;

/** Post Http data and returns final string and status on network */

public static void postHttp(String Url, Activity mActivity) {
try {
    isNetError=false;

    mConnectivityManager= (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
    mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

    if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
    {
        httppost = new HttpPost(Url);
        httpParameters = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
        httpclient = new DefaultHttpClient(httpParameters);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("text", "some Text"));


        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

        // Execute HTTP Post Request
        response = httpclient.execute(httppost);
        data = EntityUtils.toString(response.getEntity());

    }
    else
        isNetError=true;

    } catch (Exception e) {
        e.printStackTrace();
        isNetError=true;
        }

   if (responseCode == 200)
   {
        isNetError=false;
        System.out.println("final..." + data);
        }
        else
            isNetError=true;
    }

在doInBackground()中调用此方法关闭asynctask,并在onPostExecute()中检查isNetError值,并在添加权限的其他答案中提及<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

if(isNetError)
//No internet 
else
//do your stuff

答案 1 :(得分:4)

只需使用此功能检查互联网连接是否可用:

/**
   * Checks if the device has Internet connection.
   * 
   * @return <code>true</code> if the phone is connected to the Internet.
   */
    public static boolean checkNetworkConnection(Context context)
    {
        final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if(wifi.isAvailable()||mobile.isAvailable())
            return true;
        else
            return false;
    }

注意:

不要忘记在AndroidManifest.xml文件中添加权限:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 2 :(得分:0)

有效的网络连接并不一定意味着您可以访问互联网,并且OP正在询问检查 Internet连接的可用性的方法。某些WiFi网络可能要求用户在允许Internet访问之前打开浏览器并通过某种授权,因此在这种情况下仅检查有效的WiFi连接是不够的。

在没有创建GET / POST连接的情况下检查原始连接的简单方法是:

private boolean isConnected() {

    try {
        InetAddress.getByName("google.com");
    } catch (UnknownHostException e) {
        return false;
    }
    return true;
}

<强>警告1 : 完成一些测试之后,我必须警告上面的代码并不真正工作即使它出现在前几次也是如此。

代码尝试解析DNS缓存中尚未存在的主机名,因此一旦缓存成功查找,即使主机无法再访问,代码也将继续返回true所有现代操作系统都进行DNS缓存。

但是 ...在Android上, InetAddress 类有一个额外的方法,在标准JavaSE中找不到 - { {3}} 根据javadocs:

“尝试访问此InetAddress。此方法首先尝试使用ICMP(ICMP ECHO REQUEST),然后回退到远程主机的端口7(Echo)上的TCP连接。”

因此,对上述代码的可能修复将是

InetAddress.getByName("google.com").isReachable(5000);

如果ICMP数据包被阻止,检查可访问性的唯一可靠方法是通过 InetAddress.isReachable (int timeout) URLConnection创建与主机的真实连接 HttpClient 或介于两者之间的任何内容。