How To Handle With No Internet And Lost Connection In Android?
Solution 1:
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:
publicbooleanisConnectedToInternet(){
ConnectivityManagerconnectivity= (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (inti=0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
returntrue;
}
}
returnfalse;
}
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=newIntent(Settings.ACTION_MAIN);
ComponentNamecName=newComponentName("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
.
DefaultHttpClienthttpclient=newDefaultHttpClient();
HttpResponseresponse=null;
response = httpclient.execute(httpget);
intcode= response.getStatusLine().getStatusCode();
Solution 2:
publicclassCheckNetClass{
public static Boolean checknetwork(Context mContext) {
NetworkInfo info = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
returnfalse;
}
if (info.isRoaming()) {
// here is the roaming option, you can change it if you want to// disable internet while roaming, just return falsereturntrue;
}
returntrue;
}
}
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..
Solution 3:
Interesting. You have in your stack trace these lines:
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
Which mean that the offending line is
response = client.execute(post);
Which is different from the line that you mentioned. Verify the stack trace & the line that it mentions. Also, see that if you fix it by catching Exception
. If you don't, then you have a bigger problem, because UnknownHostException
is a subclass of IOException
, which you already catch.
Post a Comment for "How To Handle With No Internet And Lost Connection In Android?"