有没有办法快速检查互联网连接?

时间:2014-10-15 06:48:18

标签: android internet-connection

我需要在几秒钟内检查互联网连接。目前我使用此代码检查互联网连接,但它需要时间来检查互联网连接。在这里我使用http请求和响应,我发送一个请求与谷歌等网站,之后只有我得到回复。是否可以在发送请求时获得连接。我需要在几秒钟内检查一下,请帮助我

try {
            if (currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD){
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
                }

            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            if(urlc.getResponseCode() == 200)}  catch (IOException e) {
            Log.e(TAG, "Error checking internet connection", e);
        }

三江源

3 个答案:

答案 0 :(得分:0)

public boolean isConnectingToInternet() {
        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;
    }

答案 1 :(得分:-1)

试试这个:

private boolean isNetworkAvailable() {
        ConnectivityManager cManager = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cManager.getActiveNetworkInfo();
        if (netInfo != null) {
            if (netInfo.isAvailable() && netInfo.isConnected()) {
                return true;
            }
        }
        return false;
    }

答案 2 :(得分:-1)

试试这个 -

    private ConnectivityManager conMgr;
    private NetworkInfo activeNetwork;

    conMgr =  (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        activeNetwork = conMgr.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
// Do your task 
}