Android is wifi available

Android check internet connection [duplicate]

I want to create an app that uses the internet and I’m trying to create a function that checks if a connection is available and if it isn’t, go to an activity that has a retry button and an explanation. Attached is my code so far, but I’m getting the error Syntax error, insert «>» to complete MethodBody. Now I have been placing these in trying to get it to work, but so far no luck.

public class TheEvoStikLeagueActivity extends Activity < private final int SPLASH_DISPLAY_LENGHT = 3000; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) < super.onCreate(icicle); setContentView(R.layout.main); private boolean checkInternetConnection() < ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE); // ARE WE CONNECTED TO THE NET if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) < return true; /* New Handler to start the Menu-Activity * and close this Splash-Screen after some seconds.*/ new Handler().postDelayed(new Runnable() < public void run() < /* Create an Intent that will start the Menu-Activity. */ Intent mainIntent = new Intent(TheEvoStikLeagueActivity.this, IntroActivity.class); TheEvoStikLeagueActivity.this.startActivity(mainIntent); TheEvoStikLeagueActivity.this.finish(); >>, SPLASH_DISPLAY_LENGHT); > else < return false; Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this, HomeActivity.class); TheEvoStikLeagueActivity.this.startActivity(connectionIntent); TheEvoStikLeagueActivity.this.finish(); >> > 

The best answer resides here stackoverflow.com/a/27312494/1708390 . Just ping and see if device is actually connected to the Internet

If anyone wants to check the official document of ‘ConnectivityManager’ can visit: developer.android.com/training/monitoring-device-state/…

20 Answers 20

This method checks whether mobile is connected to internet and returns true if connected:

private boolean isNetworkConnected()

Edit: This method actually checks if device is connected to internet(There is a possibility it’s connected to a network but not to internet).

public boolean isInternetAvailable() < try < InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name return !ipAddr.equals(""); >catch (Exception e) < return false; >> 

This answer is incorrect. If you’re connected to a network that does not route to the internet this method will incorrectly return true. Note that getActiveNetworkInfo’s javadoc says you should check NetworkInfo.isConnected(), but that is also not sufficient to check that you’re on the internet. I’m looking into it further but you might have to ping a server on the internet to make sure you’re actually on the internet.

be wary of isInternetAvailable() as it can fail on «network on main thread» exceptions and thus return false even when you have a connection.

DNS addresses are cached. As a test, loop this method, then unplug your router from the internet. It keeps returning true. although it will eventually fail when the DNS cache times out (which varies a lot by DNS client). The only sure-fire way is to try and connect to something on the internet, and hope they don’t mind you flooding them with connections.

Check to make sure it is «connected» to a network:

public boolean isNetworkAvailable(Context context)

Check to make sure it is «connected» to a internet:

public boolean isInternetAvailable() < try < InetAddress address = InetAddress.getByName("www.google.com"); return !address.equals(""); >catch (UnknownHostException e) < // Log error >return false; > 

Only tells you if you are connect to a network, and not the internet. If you want crashes (for internet safe code) then use this.

My test device seem to cache the IP of the Google server, so isInternetAvailable always returns true for me. Using a different server would work, but it’s not very reliable to do so. Can I do anything about the caching?

You can simply ping an online website like google:

public boolean isConnected() throws InterruptedException, IOException

Good one but not a best one.This whole logic depends on google.com lets suppose what if google is down for some minutes then you app won’t be working for some minutes

Читайте также:  Tuf gaming b550m plus wi fi какие процессоры поддерживает

Well @ZeeshanShabbir is right , a solar flare to the part of the country of google’s main operation would take your application right out of the ball park , in such a scenario you could propably ping to a few addresses to check the same . Also , i think google wont be down if one center is down , a majority of them must be taken down for this to work also provided that your network operator survives the worldwide blackout 😀

If your app relys on a remote server (for authentication, fetching data, communication with database. etc) then you can use that server address instead of google, this way you can check for internet connectivity and the server availability at the same time. If your server is down and there is still an internet connection the app wont function properly anyways. In this case you might also want to set timeout interval for ping command using -i option like this ping -i 5 -c 1 www.myserver.com .

The above methods work when you are connected to a Wi-Fi source or via cell phone data packs. But in case of Wi-Fi connection there are cases when you are further asked to Sign-In like in Cafe. So in that case your application will fail as you are connected to Wi-Fi source but not with the Internet.

 public static boolean isConnected(Context context) < ConnectivityManager cm = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnected()) < try < URL url = new URL("http://www.google.com/"); HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); urlc.setRequestProperty("User-Agent", "test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1000); // mTimeout is in seconds urlc.connect(); if (urlc.getResponseCode() == 200) < return true; >else < return false; >> catch (IOException e) < Log.i("warning", "Error checking internet connection", e); return false; >> return false; > 

Please use this in a separate thread from the main thread as it makes a network call and will throw NetwrokOnMainThreadException if not followed.

And also do not put this method inside onCreate or any other method. Put it inside a class and access it.

The difficulties that come with threading when you just need to simply check for internet response isn’t worth the effort. Ping does the job with no struggle.

Best approach (period). Sockets, InetAddress methods are error prone specially when your device is connected to a Wifi network without an internet connection, it will continue to indicate that the internet is reachable even though it is not.

I used this one and works very well, today in late 2022, you need to use https and not http because runtime refuses to make a request in cleartext and with that exception you would always return false, as offline. changed http to https and works super well

You can use following snippet to check Internet Connection.

It will useful both way that you can check which Type of NETWORK Connection is available so you can do your process on that way.

You just have to copy following class and paste directly in your package.

/** * @author Pratik Butani */ public class InternetConnection < /** * CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */ public static boolean checkConnection(Context context) < final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connMgr != null) < NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo(); if (activeNetworkInfo != null) < // connected to the internet // connected to the mobile provider's data plan if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) < // connected to wifi return true; >else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE; > > return false; > > 
if (InternetConnection.checkConnection(context)) < // Its Available. >else < // Not Available. >

DON’T FORGET to TAKE Permission 🙂 🙂

Читайте также:  Параметры настройки интернета вай фай

You can modify based on your requirement.

You are checking whether wifi network or a cellular network is currently connected to the device. This way will not suffice for instance, when the device connects to a wifi network which doesn’t have the capability to reach the internet.

The accepted answer’s EDIT shows how to check if something on the internet can be reached. I had to wait too long for an answer when this was not the case (with a wifi that does NOT have an internet connection). Unfortunately InetAddress.getByName does not have a timeout parameter, so the next code works around that:

private boolean internetConnectionAvailable(int timeOut) < InetAddress inetAddress = null; try < Futurefuture = Executors.newSingleThreadExecutor().submit(new Callable() < @Override public InetAddress call() < try < return InetAddress.getByName("google.com"); >catch (UnknownHostException e) < return null; >> >); inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS); future.cancel(true); > catch (InterruptedException e) < >catch (ExecutionException e) < >catch (TimeoutException e) < >return inetAddress!=null && !inetAddress.equals(""); > 

This worked out pretty well for a one odd check where I am not having to manage ‘reachability’ state.

Source code for InetAddress.equals() is set to always return false (Android 30) had to resort to tostring then equals

Useful Answer but sometimes i am getting ANR’s at this line inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);

You cannot create a method inside another method, move private boolean checkInternetConnection() < method out of onCreate

you can create a thread to do continuous look up of network availability and let you know and keep retrying after an interval.

All official methods only tells whether a device is open for network or not,
If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt network detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() < @Override public void onConnectionSuccess() < Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show(); >@Override public void onConnectionFail(String msg) < Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show(); >>).execute(); 

Network Call from async Task

public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > < private OnConnectionCallback onConnectionCallback; private Context context; public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) < super(); this.onConnectionCallback = onConnectionCallback; this.context = con; >@Override protected void onPreExecute() < super.onPreExecute(); >@Override protected Boolean doInBackground(Void. params) < if (context == null) return false; boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context); return isConnected; >@Override protected void onPostExecute(Boolean b) < super.onPostExecute(b); if (b) < onConnectionCallback.onConnectionSuccess(); >else < String msg = "No Internet Connection"; if (context == null) msg = "Context is null"; onConnectionCallback.onConnectionFail(msg); >> public interface OnConnectionCallback < void onConnectionSuccess(); void onConnectionFail(String errorMsg); >> 

Actual Class which will ping to server

class NetWorkInfoUtility < public boolean isWifiEnable() < return isWifiEnable; >public void setIsWifiEnable(boolean isWifiEnable) < this.isWifiEnable = isWifiEnable; >public boolean isMobileNetworkAvailable() < return isMobileNetworkAvailable; >public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) < this.isMobileNetworkAvailable = isMobileNetworkAvailable; >private boolean isWifiEnable = false; private boolean isMobileNetworkAvailable = false; public boolean isNetWorkAvailableNow(Context context) < boolean isNetworkAvailable = false; ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()); setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()); if (isWifiEnable() || isMobileNetworkAvailable()) < /*Sometime wifi is connected but service provider never connected to internet so cross check one more time*/ if (isOnline()) isNetworkAvailable = true; >return isNetworkAvailable; > public boolean isOnline() < /*Just to check Time delay*/ long t = Calendar.getInstance().getTimeInMillis(); Runtime runtime = Runtime.getRuntime(); try < /*Pinging to Google server*/ Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = ipProcess.waitFor(); return (exitValue == 0); >catch (IOException e) < e.printStackTrace(); >catch (InterruptedException e) < e.printStackTrace(); >finally < long t2 = Calendar.getInstance().getTimeInMillis(); Log.i("NetWork check Time", (t2 - t) + ""); >return false; > > 

Источник

Читайте также:  Wo mic failed to connect to server wifi

Check whether mobile is using WIFI or Data/3G

Assuming that both WIFI and Data/3G are enabled on a device, how do I check if the user is currently using the internet over the wifi or the data plan assuming they are both enabled. So I don’t need to check if they are enabled or disabled, I would like to detect which one is the user actually using. I’ve been doing the following, is this the only solution?

WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED)

4 Answers 4

void chkStatus() < final ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifi.isConnectedOrConnecting ()) < Toast.makeText(this, "Wifi", Toast.LENGTH_LONG).show(); >else if (mobile.isConnectedOrConnecting ()) < Toast.makeText(this, "Mobile 3G ", Toast.LENGTH_LONG).show(); >else < Toast.makeText(this, "No Network ", Toast.LENGTH_LONG).show(); >> 

what is this downvote for please comment so I can work on my answers as far as I know I am very much correct

If it’s already been answered, please link to the question rather than plagiarizing the answer. Certainly the answer is correct — you copied it, after all. However, that just create duplicates on SO, making SO overall less usable.

Your answer is wrong. isAvailable() tells if network connectivity via wifi or mobile is possible, but don’t tell if there is actual connection. You must check isConnectedOrConnecting() or just isConnected().

thanks for pointing this out, I will update my answer but I believe it solved the ARMAGEDDON’s problem.

Источник

how to check wifi or 3g network is available on android device

Here, my android device supports both wifi and 3g. At particular time which network is available on this device. Because my requirement is when 3g is available I have to upload small amount of data. when wifi is available entire data have to upload. So, I have to check connection is wifi or 3g. Please help me. Thanks in advance.

4 Answers 4

/** * Checks if we have a valid Internet Connection on the device. * @param ctx * @return True if device has internet * * Code from: http://www.androidsnippets.org/snippets/131/ */ public static boolean haveInternet(Context ctx) < NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (info == null || !info.isConnected()) < return false; >if (info.isRoaming()) < // here is the roaming option you can change it if you want to // disable internet while roaming, just return false return false; >return true; > 

To get the network type you can use this code snippet:

ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); //mobile State mobile = conMan.getNetworkInfo(0).getState(); //wifi State wifi = conMan.getNetworkInfo(1).getState(); 

and then use it like that:

if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) < //mobile >else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) < //wifi >

To get the type of the mobile network I would try TelephonyManager#getNetworkType or NetworkInfo#getSubtypeName

You need to add below permission in android manifest file:

After that you can use below functions to check wifi or mobile network is connected or not

public static boolean isWifiConnected(Context context) < ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return ((netInfo != null) && netInfo.isConnected()); >public static boolean isMobileConnected(Context context)

Some references from developer.android.com are:

First get a reference to the ConnectivityManager and then check the Wifi and 3G status of the device. You’ll need the ACCESS_NETWORK_STATE permission to use this service.

 ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mWifi.isAvailable() == true) < return "Connected to WiFi"; >else if (mMobile.isAvailable() == true) < return "Connected to Mobile Network"; >else return "No internet Connection" 

Источник

Оцените статью
Adblock
detector