In my android app, I would like to test if a user can access the internet. I know I able to test if he is connected to wifi or 3G/4G, etc... but maybe the user is connected to a local network and doesn't have access to the internet.
Should I try a "ping" to google to be sure that he can download anything or does it exist a function which ensure the phone has internet ?
Thanks.
If you want to check whether the user has access to internet while s/he has connection, try to reach a web site like google with some timeout.
URL url = new URL("https://google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
If you get timeout or an error code, you can assume your app is not connected to internet.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
AndroidManifest :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
But it's already been answered here :
Here
Related
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 a code to determine if there is a network connection or not :
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
// There is an internet connection
}
But if there is a network connection and no internet this is useless. I have to ping a website and wait for a response or timeout to determine the internet connection:
URL sourceUrl;
try {
sourceUrl = new URL("http://www.google.com");
URLConnection Connection = sourceUrl.openConnection();
Connection.setConnectTimeout(500);
Connection.connect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// no Internet
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// no Internet
}
But it is a slow detection. I should learn a good and fast way to detect it.
Thanks in advance.
Try following method to detect different type of connection:
private boolean haveNetworkConnection(Context context)
{
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) Your_Activity_Name.this.getSystemService(Context.CONNECTIVITY_SERVICE);
// or if function is out side of your Activity then you need context of your Activity
// and code will be as following
// (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo)
{
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
{
if (ni.isConnected())
{
haveConnectedWifi = true;
System.out.println("WIFI CONNECTION AVAILABLE");
} else
{
System.out.println("WIFI CONNECTION NOT AVAILABLE");
}
}
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
{
if (ni.isConnected())
{
haveConnectedMobile = true;
System.out.println("MOBILE INTERNET CONNECTION AVAILABLE");
} else
{
System.out.println("MOBILE INTERNET CONNECTION NOT AVAILABLE");
}
}
}
return haveConnectedWifi || haveConnectedMobile;
}
The problem with all such schemes is that 'the internet' does not exist as an entity. There is a reason why failed connection attempts are reported as 'unreachable' or 'cannot connect to server at blahblah'. Examples:
1) You have no signal. Are you connected to the internet? Will PING succeed? Can you connect to your target server?
2) You have a signal, but your provider data allowance has been exceeded. Are you connected to the internet? Will PING succeed? Can you connect to your target server?
3) Your provider connection is fine, but their backbone router is down. Are you connected to the internet? Will PING succeed? Can you connect to your target server?
4) Your provider connection is fine, their backbone router is up but the fibre connection to country X where the server is has been interrupted by some drunken Captain and his ship's anchor. Are you connected to the internet? Will PING succeed? Can you connect to your target server?
5) All the links to the target country are up but Fred, with his ditch-digging JCB, has cut the power cable to the server farm. One of Fred's other jobs is to service the backup generator:( Are you connected to the internet? Will PING succeed? Can you connect to your target server?
6) All the hardware is up, but the server code was written by Fred before he was demoted to ditch-digger for incompetence and has now crashed, again. Are you connected to the internet? Will PING succeed? Can you connect to your target server?
7) Fred has had a day off, but his replacement, competent server admin has blocked off ICMP ping in the routers to prevent ping DOS attacks. Are you connected to the internet? Will PING succeed? Can you connect to your target server?
So, the ony way to be sure is to attempt to connect to the target server and see what happens.
You can surely detect some negative cases more quickly - surely if there is no signal, you cannot get a connection:) Past that, you should just try to connect. Tell the user what is going on, use a timeout and supply the user with a 'Cancel' button. That's about the best you can do.
How about this?
Make sure you have an active WiFi connection, now Use WifiManager.getConnectionInfo() which returns dynamic information about the current Wi-Fi connection, WifiInfo , you can get WifiInfo.getLinkSpeed(), which gives you the current link speed and check that against some minimum value.
I have an Android application which connects to the Internet. I am trapping all the possible scenarios for the connection and notice that when I don't have an Internet connection, an UnknownHostException is thrown. I am a bit confused here since getting an UnknownHostException will mean that the application was able to connect to the Internet but wasn't able to find the given URL.
Am I getting the right Exception? Could you explain why am I getting an UnknownHostException in this?
Also, can you tell the specific Exceptions for these scenarios:
When there is no Internet connection.
When the URL cannot be found.
When the request timed out.
When the website is down.
When access is denied.
I would also appreciate it if you could give me more scenarios and Exceptions. I have to trap all the possible connections and display the most appropriate message depending on the type of connection Error.
getting an UnknownHostException will mean that the application was
able to connect to the Internet
No it doesn't. It means the application was unable to resolve the host name. That could be because the host name doesn't exist, or because it was unable to connect to the Internet to resolve it.
When there is no Internet connection.
No specific exception. "There is no Internet connection" doesn't have a well-defined meaning. The condition resolves to one of the other failure modes below.
When the URL cannot be found.
If the host cannot be found, UnknownHostException. If the content part of the URL cannot be found, HTTP 404.
When the request timed out.
ConnectException with 'connection timed out' as the message, or SocketTimeoutException if it's a read timeout.
When the website is down.
ConnectException with 'connection refused' as the message.
When access is denied.
HTTP 403.
Checking Internet Connection,Just try this sample function....
public static boolean CheckInternet(Context context)
{
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return wifi.isConnected() || mobile.isConnected();
}
I hope this help....
for checking internet connectivity ....
boolean b_IsConnect = isNetworkAvailable();
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
To check internet connection, use this function .
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.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;
}
Today I found a strange thing while testing my application in android device. In My Device I have enable the WIFI connection, but due to some internal problem internet connectivity is not available, and my application was not executed and after restarting the device it works fine. So how to handle this situation.
[In my application I have validate WIFI and Mobile Network]
I had a weird problem on the network in work. I would connect phone to our network over wifi and it would connect to the network grand and the status would be "Connected to name of network". But after about 10 minutes off my phone being connected to Wifi. When I check the phone status it says "authenticating with [name of network].
This problem resulted in a while of debugging as even when it says it is "authenticating" I could still access my gmail/facebook and websites on my phone. However when I tried my connect method similar to scorpio it would return not connected to internet.
Here is mine:
/**
* Method to see if device has any access to the Internet.
* #return boolean true if connected, otherwise false.
*/
public boolean isConnectedToInternet()
{
try{
ConnectivityManager cm = (ConnectivityManager) getSystemService
(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
//Network is available but check if we can get access from the network.
URL url = new URL("http://www.Google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // Timeout 2 seconds.
urlc.connect();
if (urlc.getResponseCode() == 200) //Successful response.
{
return true;
}
else
{
Toast.makeText(this, "No connection to internet.", Toast.LENGTH_LONG).show();
Log.d("NO INTERNET", "NO INTERNET");
return false;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
Toast.makeText(this, "No connection to internet.", Toast.LENGTH_LONG).show();
return false;
}
However when the phone saids its authenticating this line here would return null.
NetworkInfo netInfo = cm.getActiveNetworkInfo();
So like I said when authenicating I could still access web on phone and apps such as facebook/gmail still worked but apps such as mine or some of my colleagues who used a similar approach above didn't.
Which obviously I can see why when I figured out why this was the case. Just got me curious to how are the apps such as facebook/gmail testing a connection to the internet.
So I was wondering should I just take a simple approach of doing this:
URL url = new URL("http://www.Google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // Timeout 2 seconds.
urlc.connect();
if (urlc.getResponseCode() == 200) //Successful response.
{
return true;
}
else
{
Toast.makeText(this, "No connection to internet.", Toast.LENGTH_LONG).show();
Log.d("NO INTERNET", "NO INTERNET");
return false;
}
Anyway the question posted is rather vague so hard to say what the internal problem you speak off is and how to fix it. Just seemed similar to a fustration.
Try this,
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
return false;
}
}
OR
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
I am trying to pull as well as push some data to and from the server via webservice. The mandatory thing that should i have to do is connectivity check. What i have done right now is , i have written a connectivity check code in each activity before it pushes/ pulls the result set from the server. I know its not a best way that i should have to code. Instead this connectivity check should be running some thing like a background , (behind the screens) and alerts the user, when the WIFI / 3G becomes low / goes down.
What is the best way to do so ?
Please let me know know your thoughts.
Thank you.
You can register a BroadcastReceiver to listen for connectivity changes. A detailed post can be found here.
Hi i do these way maybe there better
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 {
//no conection
return false;
}
}
public static boolean isInternetAvailable(Context context){
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isConnected() || mobile.isConnected()){
// Check for web site
try{
// Create a URL for the desired page
URL url = new URL("http://www.google.com");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
return true;
} catch (Exception e) {
return false;
}
}
return false;
}
The method also checks whether a certain website in this case the www.google.com is available. This might be useful as the device might be connected to a WLAN router which has no internet access. In this case wifi.isConnected() would also return true although no internet is available.
for check internet connection in android..
public static boolean isOnline(Activity act)
{
ConnectivityManager cm = (ConnectivityManager)act.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}