I am working on online app. [Problem] when internet is down or not available it gives me error [Force close], I tried to handle using broadCast Receiver but not meet exact solut
static String data = null;
private static HttpPost httppost;
private static HttpParams httpParameters;
private static int timeoutConnection = 30000;
private static HttpClient httpclient = null;
private static HttpResponse response = null;
private static int responseCode=0;
public static ConnectivityManager mConnectivityManager;
public static NetworkInfo mNetworkInfo;
public static boolean isNetError=false;
/** Post Http data and returns final string and status on network */
public static void postHttp(String Url, Activity mActivity) {
try {
isNetError=false;
mConnectivityManager= (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
{
httppost = new HttpPost(Url);
httpParameters = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
httpclient = new DefaultHttpClient(httpParameters);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("text", "some Text"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
data = EntityUtils.toString(response.getEntity());
}
else
isNetError=true;
} catch (Exception e) {
e.printStackTrace();
isNetError=true;
}
if (responseCode == 200)
{
isNetError=false;
System.out.println("final..." + data);
}
else
isNetError=true;
}
call this method in your doInBackground() of asyntask, and onPostExecute() check isNetError value and as mentioned in other answer of adding permission <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
if(isNetError)
//No internet
else
//do your stuff
Just use this function to check whether the Internet connection is available or not:
/**
* Checks if the device has Internet connection.
*
* @return <code>true</code> if the phone is connected to the Internet.
*/
public static boolean checkNetworkConnection(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isAvailable()||mobile.isAvailable())
return true;
else
return false;
}
Don't forget to add permission inside the AndroidManifest.xml file: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
A valid network connection does not necessarily mean you can access the Internet, and the OP was asking for ways to check the availability of an Internet Connection. Some WiFi networks might require users to open a browser and go through some kind of authorization before allowing Internet access, so just checking for a valid WiFi connection is not sufficient in this case.
A naive approach to checking for raw connectivity without creating a GET/POST connection would be:
private boolean isConnected() {
try {
InetAddress.getByName("google.com");
} catch (UnknownHostException e) {
return false;
}
return true;
}
WARNING1: Having done some testing I must warn that the code above DOES NOT REALLY WORK even if it appears so the first couple of times.
The code attempts to resolve a host name that is not already in the DNS cache, so once a successful lookup has been cached the code will continue returning true even if the host is not reachable anymore since all modern OS's do DNS caching.
BUT... On Android the InetAddress class has an additional method that is not found in the standard JavaSE - InetAddress.isReachable (int timeout) which according to javadocs:
"Tries to reach this InetAddress. This method first tries to use ICMP (ICMP ECHO REQUEST), falling back to a TCP connection on port 7 (Echo) of the remote host."
So a possible fix to the code above would be
InetAddress.getByName("google.com").isReachable(5000);
In cases when ICMP packets are blocked the only reliable way to check reachability would be to create a real connection to your host either via URLConnection, HttpClient, Socket or anything in between.