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