Click here to Skip to main content
13,087,235 members (61,060 online)
Rate this:
Please Sign up or sign in to vote.
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.
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 7:30am
Updated 5-Jul-13 22:11pm

1 solution

Rate this: bad
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]
Kartik Lalan 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 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
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.170813.1 | Last Updated 6 Jul 2013
Copyright © CodeProject, 1999-2017
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