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;
}
Related
I know this have been asked a lot of times, but none of this answer resolve my problem, my question is when my modem is restarting starts to turn on leds such as power(obviously), dns, wireless, DSL and internet, when internet led is in yellow colour means that there is internet but when is in red colour all the codes I have(see below) return to true when is obviously that there is no internet(you can't navigate this way)
here is the codes of methods (isConnectingToInternet,isOnline,haveNetworkConnection) I have (and all returning true when internet led is red)
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;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
How can I verify when led is red? any method? thanks
I answered that within another question, but it might be an answer to this one too. My solution, basically, is based on setting a Socket to Google on the 80 port.
I use the following code on many of my projects:
Socket socket;
final String host = "www.google.com";
final int port = 80;
final int timeout = 30000; // 30 seconds of timeout
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("GoogleSock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("GoogleSock", "After a reasonable amount of time, I'm not able to connect, Google is probably down!");
}
catch (IOException ioe) {
Log.e("GoogleSock", "Hmmm... Sudden disconnection, probably you should retry once again!");
}
If response time is important to you, this might be tricky, though. Precisely on UnknownHostExceptions, it may take longer to timeout, about 45 seconds. If you have a connection issue, this shouldn't be fired though. Actually, any of the exceptions being thrown would mean you probably at 99.999% have a connection issue.
Anyway, if response time is important to you and you want to hedge your bets, you could solve this by two ways:
Don't use a host, use an IP address instead. You may get several Google's IPs just using ping several times on the host. For instance:
shut-up#i-kill-you ~/services $ ping www.google.com
PING www.google.com (173.194.40.179) 56(84) bytes of data.
Another workaround would be starting a WatchDog thread and finish the connection attempt after the required time. Evidently, forcely finishing would mean no success, so in your case, Google would be down.
I am creating an application to check the status of the mobile network.
I use NetworkInfo.State.CONNECTED to check the connectivity. It works fine on my emulator.
But when the user makes a call the Network info state is SUSPENDED(But the user is connected to the network) What does the suspended code indicate?
Also when I run the application on a device, the network state is given as DISCONNECTED. But the user is connected to the network and can recevice/give calls. The NetworkInfo.getReason() is given as datadisconnected in this case.
Can someone please help met o check the mobile connectivity to the network.
Thanks in advance.
public class NetWorkCheck{
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo, lanInfo;
public Boolean checkNow(Context con){
try{
connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifiInfo.isConnected() || mobileInfo.isConnected())
{
return true;
}
}
catch(Exception e){
System.out.println("CheckConnectivity Exception: " + e.getMessage());
}
return false;
}
}
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 would like to know if the mobile network is enabled or disabled.
My application is designed to help the user when he receives a phone call, and to do this I need Internet access. Thus, I would like to display an information box when the user access the application for the first time if Wi-Fi has a sleep policy and Mobile network is disabled. (I need Internet within milliseconds after the phone start ringing).
I found Settings.System.WIFI_SLEEP_POLICY, but I can't find any information on how to check if mobile network is disabled (when Wi-Fi is on and working).
Any help would be appreciated!
Edit:
The problem is that I want to know if mobile network is turned of by the user (while the phone could have WiFi access at the time).
I finally found a solution. Apparently not all phones have this option:
Home > Menu > Settings > Wireless & networks > Mobile network (checkbox)
However, for those who do, this method will work:
/**
* #return null if unconfirmed
*/
public Boolean isMobileDataEnabled(){
Object connectivityService = getSystemService(CONNECTIVITY_SERVICE);
ConnectivityManager cm = (ConnectivityManager) connectivityService;
try {
Class<?> c = Class.forName(cm.getClass().getName());
Method m = c.getDeclaredMethod("getMobileDataEnabled");
m.setAccessible(true);
return (Boolean)m.invoke(cm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
apparently there is an alternative, more clean solution then the Reflection approach:
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
int type = networkInfo.getType();
String typeName = networkInfo.getTypeName();
boolean connected = networkInfo.isConnected()
networkInfo.getType() will return '0' when connected to mobile network
or '1' when connected trough WIFI. networkInfo.getTypeName() will return
the strings "mobile" or "WIFI". and networkInfo.isConnected() will tell you whether or not you have an active connection.
UPDATE FOR ANDROID 5.0+ (API 21+)
Calling getMobileDataEnabled via the reflection leads to NoSuchMethodException on Android 5.0+ on some devices. So in addition to accepted answer you may wanna do second check if NoSuchMethodException is thrown.
...
catch(NoSuchMethodException e)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
isDataEnabled = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
}
you can use below code this is working for all API versions:
ConnectivityManager cm =
(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if(isConnected)
{
if(activeNetwork.getType()==ConnectivityManager.TYPE_MOBILE)
return true;
else
return false;
}
else
return false;
PackageManager pm = context.getPackageManager();
boolean hasTelephony = pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
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;
}