3

To detect whether internet is connected or not I am using the following code:

             public boolean netConnect(Context ctx)
            {

                ConnectivityManager cm;
                NetworkInfo info = null;
                try
                {
                    cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
                    info = cm.getActiveNetworkInfo();
                }
                catch (Exception e)
                {

                    e.printStackTrace();
                }
                if (info != null)
                {
                    return true;

                }
                else
                {
                    return false;
                }
            }

Which is working perfectly fine .

But I want to know if the internet connection goes off at the time when app is downloading some files from server(I mean to say in between the process) is there anyway to detect that and display that internet connection lost or weak?

Navdroid
  • 4,453
  • 7
  • 29
  • 47
  • You can take refence from here : http://stackoverflow.com/questions/4238921/android-detect-whether-there-is-an-internet-connection-available/4239019#4239019 – mayur rahatekar Feb 24 '12 at 11:20

2 Answers2

4

You will have to use a BroadcastReceiver in all you Activities. I eventually ended up writing a super class for this.

Now, whenever I write an App I do not extend Activity, I always extends a dummy class that I create say MyActivity. That way whenever a requirement changes I only change MyActivity and all my classes are updated.

For your particular case, I wrote a superclass that is available at : https://github.com/sfarooq/A-droid-lib/ Look at the ConnectedActivity class in the network package. It shows a dialog whenever connection is lost and dismisses it when connection is restored. To use it just extend ConnectedActivity in the Activities you want. To use it throughout the app, I would recommend making your own superclass as mentioned above and have that extend ConnectedActivity so you are able to change stuff later (also helpful if you want to add custom dialog and menus later, you'll only have to add it to your super class).

Saad Farooq
  • 13,172
  • 10
  • 68
  • 94
2

There is special system action, that notify apps about changing of state of internet access. For getting it you need create BroadcastReceiver. See this question for more info.

Community
  • 1
  • 1
Jin35
  • 8,602
  • 3
  • 32
  • 52