3

我正在开发一个android应用程序,我想知道检查互联网连接是否存在的最佳方法。我尝试过使用connectivity managernetworkinfo上课,但无济于事,因为我的应用程序在没有网络的情况下不断崩溃,否则我会去HttpConnection方法。有人可以提出宝贵的建议。

4

4 回答 4

3
    URL myurl = new URL(url);
    URLConnection connection = myurl.openConnection();
    connection.setConnectTimeout(20 * 1000);
    HttpURLConnection httpConnection = (HttpURLConnection) connection;
    int responseCode = -1;
    try {
        responseCode = httpConnection.getResponseCode();
    } catch (Exception e1) {                    
            throw e1;                   
    }
    if (responseCode == HttpURLConnection.HTTP_OK) {
          //connection is OK and do what you want
          //...
    }
    else
    {
          //connection is not OK
          httpConnection.disconnect();
    }
于 2012-06-16T11:10:08.540 回答
0

这是一个古老的问题,但我正在做的是在这里回答以使其对其他人也有用。创建一个如下所示的类:

public class ConnectionDetector {

    private Context context;

    public ConnectionDetector(Context context) {
        this.context = context;
    }

    public boolean isConnectedToInternet() {

        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }
}

method然后像这样调用类activity来检查连接:

 if(new ConnectionDetector(context).isConnectedToInternet()){
   //Connected 
   //do what you want to do here
 } else{
   // Not connected
   // show appropriate message
 }
于 2015-06-19T11:08:48.520 回答
0

Udacity 优秀的 Advanced Android App Development 课程使用 getActiveNetworkInfo()

https://www.udacity.com/course/advanced-android-app-development--ud855

/**
 * @param context Context used to get the ConnectivityManager
 * @return true if network has connectivity (i.e. is reachable), else return false
 */
static public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return ((activeNetworkInfo != null)
            && activeNetworkInfo.isConnectedOrConnecting());
}

顺便说一句:Clairvoyant 的好答案使用了 getAllNetworkInfo,现在在 API 级别 23 中已弃用。

Android 文档说使用 getAllNetworks() 和 getNetworkInfo(android.net.Network) 代替。

http://developer.android.com/reference/android/net/ConnectivityManager.html#getAllNetworkInfo()

我更新了 Clairvoyant 的方法如下并使用它,直到我看到上面 Udacity 的更简单的 isNetworkAvailable 方法。

/**
 * @return true if network has connectivity (i.e. is reachable), else return false
 */
boolean hasConnectivity(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager != null) {
        Network[] networks = connectivityManager.getAllNetworks();
        if ((networks != null)
                && (networks.length > 0)) {
            for (Network network : networks) {
                NetworkInfo info = connectivityManager.getNetworkInfo(network);
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}
于 2015-10-25T23:15:31.613 回答
0

我建议您检查异常以指定发生了什么错误,您可以根据错误提示用户。

try {
    URL url = new URL("https://google.com");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(10000);
    connection.connect();
    success = connection.getResponseCode() == 200;
} catch (IOException e) {
    //use the function here
    onError(this,e);
}

public void onError(Activity activity,Throwable e){
        try {
            e.printStackTrace();
            FirebaseCrash.report(e);

            if (e instanceof HttpException) {
                Response body = ((HttpException) e).response();
                if (body.code() == 401) {
                    Toast.makeText(activity, "Not Authorized Access", Toast.LENGTH_SHORT).show();
                } else if (body.code() == 404) {
                    Toast.makeText(activity, "Request not found", Toast.LENGTH_SHORT).show();
                } else if (body.code() == 400) {
                    Toast.makeText(activity, "Bad Request", Toast.LENGTH_SHORT).show();
                } else if (body.code() == 500) {
                    Toast.makeText(activity, "Internal Server Error", Toast.LENGTH_SHORT).show();
                } else {
                    Log.e(Constants.TAG, "Error : Code HTTP = " + body.code());
                }
            }else if(e instanceof ConnectException || e instanceof SocketException){
                Toast.makeText(activity, "No Internet Connection", Toast.LENGTH_SHORT).show();
            } else if (e instanceof UnknownHostException) {
                Toast.makeText(activity, "Make Sure Your Internet Connection is Properly Connected", Toast.LENGTH_SHORT).show();
            } else if (e instanceof SSLHandshakeException || e instanceof SSLPeerUnverifiedException) {
                Toast.makeText(activity, "Server Connection Problem..Please Try Again", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(activity, "Data Load Error", Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception ex){
            FirebaseCrash.report(e);
            e.printStackTrace();
        }
    }
于 2016-10-18T15:24:00.297 回答