开发者

Check the Internet Connectivity in Android

I am trying to pull as well as push some data to and from the server via webservice. The mandatory thing that should i have to do is connectivity check. What i have done right now is , i have written a connectivity check code in each activity before it pushes/ pulls the result set from the server. I know its not a best way that i should have to code. Instead this connectivity check should be running some thing like a background , (behind开发者_Go百科 the screens) and alerts the user, when the WIFI / 3G becomes low / goes down.

What is the best way to do so ?

Please let me know know your thoughts.

Thank you.


You can register a BroadcastReceiver to listen for connectivity changes. A detailed post can be found here.


Hi i do these way maybe there better

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


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

The method also checks whether a certain website in this case the www.google.com is available. This might be useful as the device might be connected to a WLAN router which has no internet access. In this case wifi.isConnected() would also return true although no internet is available.


for check internet connection in 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;

     }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜