Android - How to check, device has Internet connection? - android

This code works:
public static boolean isConnected()
{
ConnectivityManager cm = (ConnectivityManager)App.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null) {
if (ni.getType() == ConnectivityManager.TYPE_WIFI)
if (ni.isConnected())
return true;
if (ni.getType() == ConnectivityManager.TYPE_MOBILE)
if (ni.isConnected())
return true;
if (ni.getType() == ConnectivityManager.TYPE_ETHERNET)
if (ni.isConnected())
return true;
}
return false; //none of connections available
}
The question is: do we also have to check TYPE_MOBILE_DUN, TYPE_WIMAX and TYPE_VPN?
Can a device be connected to the Internet over Bluetooth?

Just one comment. Think what do you need and remember to be connected to a wifi router doesn't mean you have internet connection or that you are able to reach any point of interest like a backend server.
If your app needs to access a service to work, may be the best way it is to check if you can reach it in an early stage through an async call and only proceed if you could validate that connection.

Try to make a simple GET request to http://www.google.com. If your response code is 200 or 400 Then the internet connection exists.
protected static boolean hasInternetAccess()
{
try
{
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:1");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30);
urlc.connect();
// http://www.w3.org/Protocols/HTTP/HTRESP.html
if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
{
// Requested site is available
return true;
}
}
catch (Exception ex)
{
// Error while trying to connect
return false;
}
return false;
}
For more info, refer to: The perfect function to check Android internet connectivity including bluetooth pan

This is all I use:
public static boolean isOffline() {
ConnectivityManager cm = (ConnectivityManager) BigOvenApplication.getInstance()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo == null || !netInfo.isConnected();
}
I don't think you need anything more than that.

Just call the method isConnectedToNetwork to check whether it has connection or not. Write this method in a common class file. Thereby you can use simple methodcall where ever you need.
public static boolean isConnectedToNetwork(Context thisActivity) {
ConnectivityManager connMgr = (ConnectivityManager) thisActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
return true;
}
return false;
}
Check before you start the operation.
//thisActivity means getActivity() for fragments
if (isConnectedToNetwork(thisActivity)) {
// your operation code follows
} else {
//show alert box that there is no internet connection
}

Related

Check continuously if internet is available

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.

How to check the state of 3G in my app:

Actually i had used the following code to check the wifi is active or not (its working fine).
I just want to confirm that can i use the same code to check the 3G active state:
public boolean checkwifi()
{
ConnectivityManager connec = (ConnectivityManager) this.getSystemService(this.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Here if condition check for wifi and mobile network is available or not.
// If anyone of them is available or connected then it will return true, otherwise false;
if (wifi.isConnected()) {
return true;
}
else if (mobile.isConnected()) {
return true;
}
return false;
}
to check if your connection(WIFI or Mobile ) is On or Off , try this :
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) {
//we are connected to a network
connected = true;
}
else
connected = false;
Yes - this code should work. I've got an extra bit of functionality you may want to implement:
public static boolean isOnline(Context context) {
//ConnectivityManager is used to check available network(s)
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
This does the same as your code - it will tell you if you are online via any method (3G or WiFi), but it's a bit more concise.
** EDIT **
Here's the source for that method - it will return null if no active network connection or will return a NetworkInfo object for a current connection:
/**
* Return NetworkInfo for the active (i.e., connected) network interface.
* It is assumed that at most one network is active at a time. If more
* than one is active, it is indeterminate which will be returned.
* #return the info for the active network, or {#code null} if none is active
*/
public NetworkInfo getActiveNetworkInfo() {
enforceAccessPermission();
for (NetworkStateTracker t : mNetTrackers) {
NetworkInfo info = t.getNetworkInfo();
if (info.isConnected()) {
return info;
}
}
return null;
}

How to detect when WIFI is connected to internet?

I am building an Android app and I use the code below to detect whether there is a network connection. It works well and detects both mobile and WIFI networks.
My problem is how to detect an actual internet connection. The code below returns true when connected to WIFI however the WIFI might not necessarily be connected to the Internet.
The code
protected 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;
}
} //end checkInterneConnection method
Thanks for your time.
Mel
You should try to reach an internet adress. Therefor you should check the InetAdress class and the method isReachable: http://developer.android.com/reference/java/net/InetAddress.html#isReachable%28int%29
This piece of code will check whether your device Internet conecction, If the signal is Poor it will show a Toast other wise not,
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = conMan.getActiveNetworkInfo();
if(Info == null){
Toast.makeText(RegisterActivity.this,"Network Connection Failed! ", Toast.LENGTH_SHORT).show();
}
You can try ping http://google.com or doing something like this to confirm it's ok to visit internet.
You should try this:
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)
m_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;
}
And to check only wifi is simpler:
private boolean isWifiConnected() {
int WIFI_STATE = wifi.getWifiState();
if(WIFI_STATE == WifiManager.WIFI_STATE_ENABLED)
return true;
return false;
}
This code will really test the internet connection:
public static boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("google.com");
return address.isReachable(2000); //This really tests if the ip, given by the url, is reachable
//return !address.equals(""); //This just tests if the IP is available but it could be taken in a previous request when internet was available
} catch (Exception e) {
Log.d("Internet check", "Unable to reach the url: "+url);
}
return false;
}

Check Internet connection problem in android?

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();
}

Check the Internet Connectivity in Android

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;
}

Categories

Resources