簡體   English   中英

檢查Android中的互聯網連接

[英]Check the Internet Connectivity in Android

我正在嘗試通過Web服務向服務器中以及從服務器中推入和推入一些數據。 我必須要做的強制性事情是連接檢查。 我現在所做的是,在每個活動從服務器中推送/提取結果集之前,我已經在每個活動中編寫了連接檢查代碼。 我知道這不是我應該編碼的最佳方法。 相反,當WIFI / 3G變低/掉線時,此連接檢查應在屏幕后面運行諸如background的操作,並警告用戶。

最好的方法是什么?

請讓我知道您的想法。

謝謝。

嗨,我這樣做的方式也許更好

private boolean checkInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    // test for connection
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        //no conection
        return false;
    }
}

您可以注冊BroadcastReceiver來偵聽連接更改。 可以在這里找到詳細的帖子。

public static boolean isInternetAvailable(Context context){
        ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if(wifi.isConnected() || mobile.isConnected()){
            // Check for web site       
            try{
                // Create a URL for the desired page
                URL url = new URL("http://www.google.com");
                // Read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                in.close();
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        return false;
    }   

該方法還檢查在這種情況下www.google.com是否可用的某個網站。 這可能很有用,因為設備可能已連接到無法訪問Internet的WLAN路由器。 在這種情況下,即使沒有可用的互聯網, wifi.isConnected()也將返回true

用於檢查android中的互聯網連接。

public static boolean isOnline(Activity act) 
     {
         ConnectivityManager cm = (ConnectivityManager)act.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) 
        {
            return true;
        }
        return false;

     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM