Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Android
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.
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 5-Jul-13 8:30am
Edited 5-Jul-13 23:11pm
v4

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi Kartik, Please refer to below code for checking internet connection.
 
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]
  Permalink  
Comments
Kartik Lalan at 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.
Kartik Lalan at 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)

  Print Answers RSS
0 OriginalGriff 350
1 Jochen Arndt 150
2 Richard MacCutchan 135
3 PIEBALDconsult 110
4 Sergey Alexandrovich Kryukov 104
0 OriginalGriff 6,055
1 DamithSL 4,621
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,500
4 Sergey Alexandrovich Kryukov 3,294


Advertise | Privacy | Mobile
Web03 | 2.8.141220.1 | Last Updated 6 Jul 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100