I have the following code check if I have active internet connection:
private boolean hasNetworkAccess() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.screens.company").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(3000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e("NETWORK", "Error checking internet connection.");
}
return false;
}
When I'm connected to my Wi-Fi at home / connected to my phone's hotspot / connected directly to my router - everything is OK and it shows I have active connection.
When every I'm connecting my computer to an Portable Router (TP-LINK) I get the error.
What could be the error just I'm my portable router?
P.S I checked everything else is working when I'm connected to the router like internet browser, YouTube, etc.
Error stack trace:
java.net.SocketTimeoutException: failed to connect to www.screens.company/80.179.142.52 (port 80) after 3000ms
Try this
Check to make sure it is connected to a network:
public boolean isNetworkAvailable(Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Alternate solution
public boolean isInternetAvailable() {
try {
final InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
-Permission required
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).
Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?
Try this:
It's really simple and fast:
public boolean isInternetAvailable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
sock.close();
return true;
} catch (IOException e) { return false; }
}
Then wherever you want to check just use this:
if (isInternetAvailable("8.8.8.8", 53, 1000)) {
// Internet available, do something
} else {
// Internet not available
}
The first problem you should make it clear is what do you mean by whether internet is available?
Not connected to wifi or cellular network;
Connected to a limited wifi: e.g. In a school network, if you connect to school wifi, you can access intranet directly. But you have to log in with school account to access extranet. In this case, if you ping extranet website, you may receive response because some intranet made auto redirect to login page;
Connected to unlimited wifi: you are free to access most websites;
The second problem is what do you want to achieve?
As far as I understand your description, you seems want to test the connection of network and remind user if it fails. So I recommend you just ping your server, which is always fine if you want to exchange data with it.
You wonder whether there is a better way to test connectivity, and the answer is no.
The current TCP/IP network is virtual circuit, packet-switched network, which means there is no a fixed 'path' for the data to run, i.e. not like a telephone, we have a real connection between two users, we can know the connection is lost immediately after circuit is broken. We have to send a packet to the destination, and find no response, then we know, we lose the connection (which is what ping -- ICMP protocol -- does).
In conclusion, we have no better way to test the connectivity to a host other than ping it, that is why heartbeat is used in service management.
Try the following:
public boolean checkOnlineState() {
ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NInfo = CManager.getActiveNetworkInfo();
if (NInfo != null && NInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
Don't forget the access:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Else:
if (InetAddress.getByName("www.google.com").isReachable(timeout))
{ }
else
{ }
On checking this issue it found that We cannot determine whether an active internet connection is there, by using the method specified in the developer site:
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
This will only check whther ther active connection of wifi.
So I found 2 methods which will check whether there is an active internet connection
1.Ping a website using below method
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 30 second time out.
httpURLConnection.setConnectTimeout(30000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
isAvailable = true;
}
2.Check the availability of Google DNS using socket
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, 1000); // this will block no more than timeoutMs
sock.close();
return true;
}
The second method is little faster than 2nd method (Which suits for my requirement)
Thanks all for the answers and support.
I wanted to comment, but not enough reputation :/
Anyways, an issue with the accepted answer is it doesn't catch a SocketTimeoutException, which I've seen in the wild (Android) that causes crashes.
public boolean isInternetAvailable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
sock.close();
return true;
} catch (IOException e) {
return false;
} catch (SocketTimeoutException e) {
return false;
}
}
//***To verify internet access
public static Boolean isOnline(){
boolean isAvailable = false;
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("https://stackoverflow.com/");
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection) url.openConnection();
// 2 second time out.
httpURLConnection.setConnectTimeout(2000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
isAvailable = true;
} else {
isAvailable = false;
}
} catch (IOException e) {
e.printStackTrace();
isAvailable = false;
}
if (isAvailable){
return true;
}else {
return false;
}
}
ConnectivityManager will not be able to tell you if you have active connection on WIFI.
The only option to check if we have active Internet connection is to ping the URL. But you don't need to do that with every HTTP request you made from your App.
What you can do:
Use below code to check connectivity
private boolean checkInternetConnection()
{
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
And while making rest call using HTTP client set timeout like 10 seconds. If you don't get response in 10 seconds means you donot have active internet connection and exception will be thrown (Mostly you get response within 10 seconds). No need to check active connection by pinging everytime (if you are not making Chat or VOIP app)
Maybe this can help you:
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// Test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
}
else {
return false;
}
}
Try this method, this will help you:
public static boolean isNetworkConnected(Context context)
{
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
return true;
}
}
return false;
}
You can try this for check Internet connectivity:
/**
* Check Connectivity of network.
*/
public static boolean isOnline(Context context) {
try {
if (context == null)
return false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
if (cm.getActiveNetworkInfo() != null) {
return cm.getActiveNetworkInfo().isConnected();
} else {
return false;
}
} else {
return false;
}
}
catch (Exception e) {
Log.error("Exception", e);
return false;
}
}
In your activity you call this function like this.
if(YourClass.isOnline(context))
{
// Do your stuff here.
}
else
{
// Show alert, no Internet connection.
}
Don't forget to add ACCESS_NETWORK_STATE PERMISSION:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Try this if you want to just ping the URL:
public static boolean isPingAvailable(String myUrl) {
boolean isAvailable = false;
try {
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 30 second time out.
httpURLConnection.setConnectTimeout(30000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
isAvailable = true;
}
} catch (Exception e) {
isAvailable = false;
e.printStackTrace();
}
return isAvailable;
}
Typically when building my android applications that require API calls etc, I check the NetworkAvailability before making such calls like so:
public boolean networkIsAvailable() {
boolean result = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
if (activeNetworkInfo.isConnected()) {
result = true;
}
}
return result;
}
Simple enough... But what happens when say a user is on a device that has no Mobile Connection and is connected to a Wifi Network, but that Wifi Network doesn't have internet access.
Are there options aside from catching a java.net.UnknownHostException to test for actual internet access?
You can use this:
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
Remember this: "As Tony Cho also pointed out in this comment below, make sure you don't run this code on the main thread, otherwise you'll get a NetworkOnMainThread exception (in Android 3.0 or later). Use an AsyncTask or Runnable instead."
Source: Detect if Android device has Internet connection
I have built an android application that requires continuous internet access. I want to check it continuously, not only if the device is connected to a WiFi but also that it can retrieve data (sometimes it is connected to WiFi but still has no internet access). Is there an approach to achieve this? Also will this approach be friendly for the user (will it eat up more data) ?
you can use this.
public boolean isConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
isConnected used for checking connection to network, then use following code to check Internet accessibility
public boolean isOnline() {
if (isConnected()) {
try {
URL url = new URL("http://www.google.com"); // or any valid link.
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
you can call this from server class
I want to check it continuously, not only if the device is connected
to a WiFi but also that it can retrieve data (sometimes it is
connected to WiFi but still has no internet access). Is there an
approach to achieve this?
Yes, it's possible. Code from here:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
You can run this before making network requests.
Alternatively you can implement a BoadcastReceiver and be notified on network connection changes. You need to register for the action:
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
More info in the developer guide.
hello sir in login page i am validating username and password from server database. if net is there means my application is working properly. if i disconnect internet means my application run means it show error application was not responding. how to eliminate this type of error
i try this code
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Main.this, "Please Enter Username and Password", Toast.LENGTH_LONG).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("server url/login.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (IOException e) {
System.out.println(e);
//alertDialog.cancel();
}
if(buffer.charAt(0)=='Y')
{
Intent intent=new Intent(getApplicationContext(),ManagerHandset.class);
startActivity(intent);
}
else
{
Toast.makeText(Main.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
}
}
}
});
if i want disconnect my net means how to show alert net is not available
You can check your internet connection through this type of function:
public boolean isNetworkAvailable(Context context) {
boolean value = false;
ConnectivityManager connec = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
value = true;
}
// Log.d ("1", Boolean.toString(value) );
return value;
}
Remember you have added following permissions in your Manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Edit
if (isNetworkAvailable(getApplicationContext()))
{
// Do whatever you want to do
}
else{
new AlertDialog.Builder(YourActivitName.this)
.setTitle("Error")
.setMessage("Your Internet Connection is not available at the moment. Please try again later.")
.setPositiveButton(android.R.string.ok, null)
.show();
}
Hope this will work for you...
You can use something like this:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
If it returns true continue with your normal code else show a message.. also in your manifest file add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The check of the network status before stating a web call is a good habit and all the methods explained in the other responses are right. Link to the android doc.
If your application is not responding when the network is disconnected, it means you are stating your HTTP request on the main thread. You should NEVER do that.
Even if it works fine when the network is up over a Wifi connexion, you will face the same "not responding" error over a slow EDGE connection.
To make the HTTP request outside the main thread you should use an AsyncTask, the principle is explained in the android doc.
check the internet connection if net is avaible or not..
private boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
return true;
}
else
{
return false;
}
}