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?
You will have to use a
BroadcastReceiverin all youActivities. I eventually ended up writing a super class for this.Now, whenever I write an
AppI do not extendActivity, I always extends a dummy class that I create sayMyActivity. That way whenever a requirement changes I only changeMyActivityand 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
ConnectedActivityclass in thenetworkpackage. It shows a dialog whenever connection is lost and dismisses it when connection is restored. To use it just extendConnectedActivityin theActivitiesyou want. To use it throughout the app, I would recommend making your own superclass as mentioned above and have that extendConnectedActivityso 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).