How to handle with no Internet and lost connection in Android?
You can either create method
or some class may be where you can instantiate method as static
.
Here is a method named isConnectedToInternet()
which checks whether internet is connected or not. Return boolean on the basis of connection back to the calling function.
Snippet:
public boolean isConnectedToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().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;
}
You can decide on the basis of return value of isConnectedToInternet()
whether to execute AysncTask
or Throw some pop up. Here i've been added user to brought in his Data Settings
.
Something like these:
if(isConnectedToInternet())
{
// Run AsyncTask
}
else
{
// Here I've been added intent to open up data settings
Intent intent=new Intent(Settings.ACTION_MAIN);
ComponentName cName = new ComponentName("com.android.phone","com.android.phone.NetworkSetting");
intent.setComponent(cName);
}
As you mentioned what if you looses connection in between. You can check the status code as per the reponse of httpclient and pop up relevant information to user.
You can integrate these snippet under AysncTask
.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
response = httpclient.execute(httpget);
int code = response.getStatusLine().getStatusCode();
public class CheckNetClass {
public static Boolean checknetwork(Context mContext) {
NetworkInfo info = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option, you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
}
Use this class to check internet availability like:
if (CheckNetClass.checknetwork(getApplicationContext()))
{
new GetCounterTask().execute();
}
else
{
Toast.makeText(getApplicationContext(),"Sorry,no internet connectivty",1).show();
}
Hope this helps..