Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having an application which uses internet connection for receiving data from webservice. But at times of no internet connection my app is forcibly closed.So to prevent this I want to check whether the device is connected to internet or not.
Java
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}



I have tried the above most common code from google, but problem with that is that even with no internet connection it returns that the device is having internet. Please help me with some working code.
Posted
Updated 5-Jul-13 22:11pm
v4

1 solution

Hi Kartik, Please refer to below code for checking internet connection.

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


For detecting connection status in android please refer to this [LINK]
 
Share this answer
 
Comments
[no name] 6-Jul-13 6:02am    
Sudhakar Shinde thank you for your effort but this one has same problem, even on no internet connection it shows presence of internet.
Somewhere I found that there might be possibility that while working no AVD you might face prob, so i will try it over my phone and let you know.
[no name] 6-Jul-13 6:43am    
Your answer was mostly correct. After stopping internet (Pressing F8 in AVD) it will work properly. Since disconnecting internet with our PC wont make any difference , we need to explicitly stop internet inside AVD.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900