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