Проверить подключение интернет android

how to detect internet connection in android studio

I have following code to detect if there is internet connection available or not. But if I have no internet connection only the data connection is «ON» it still works. what I should do?

 ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE); NetworkInfo ninfo = cManager.getActiveNetworkInfo(); if(ninfo!=null && ninfo.isConnected()) < Toast.makeText(this, "Available",Toast.LENGTH_LONG).show(); >else

Check which connection Android is recognizing: Toast.makeText(this, «Available: » + ninfo.getTypeName(),Toast.LENGTH_LONG).show();

2 Answers 2

Use this NetworkUtils class:

import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class NetworkUtils < private static int TYPE_WIFI = 1; private static int TYPE_MOBILE = 2; private static int TYPE_NOT_CONNECTED = 0; public static int getConnectivityStatus(Context context) < ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) < if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.getState() == NetworkInfo.State.CONNECTED) < return TYPE_WIFI; >else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE && networkInfo.getState() == NetworkInfo.State.CONNECTED) < return TYPE_MOBILE; >> return TYPE_NOT_CONNECTED; > public static boolean isNetworkConnected(Context context) < int networkStatus = getConnectivityStatus(context); if (networkStatus == TYPE_WIFI || networkStatus == TYPE_MOBILE) < return true; >else < return false; >> > 
if(NetworkUtils.isNetworkConnected(this))

use the ConnectivityManager class. here is the java class:

 ConnectivityManager manager =(ConnectivityManager) getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = manager.getActiveNetworkInfo(); if (null != activeNetwork) < if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)< //we have WIFI >if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) < //we have cellular data >> else < //we have no connection :( >

do not forget to ask for the permissions in AndroidManifest.xml :

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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.

Читайте также:  Dir 842 нет интернета

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

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

Источник

Как постоянно проверять имеется ли подключение к интернету?

К примеру включили интернет, вывелось соответствующее сообщение, потом отключили его и опять получили соответствующее сообщение. Те мониторить состояние интернета в любой момент времени, а не единоразово

2 ответа 2

Вам нужно не мониторить состояние интернета, а получать уведомления о его изменении

Определение состояния подключения в момент времени:

boolean checkInternet(Context context)

BroadcastReceiver на изменение состояния сети:

public class NetworkChangeReceiver extends BroadcastReceiver < @Override public void onReceive(final Context context, final Intent intent) < if(checkInternet(context))< Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); >> 

И в манифесте определить сам ресивер:

И обязательно пермишен на получение состояния сети:

Получаем ConnectivityManager и выбираем какие броадкасты будем слушать:

connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); BroadcastReceiver connectivityStatusReceiver = new NetworkConnectionStatusReceiver(); 

Когда нужно начать мониторить состояние интернета запускаем прослушку соответствующих интентов:

context.registerReceiver(connectivityStatusReceiver, NETWORK_INTENT_FILTER)) 

Ну и собсно проверяем наличие интернета:

protected boolean hasConnection() < NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) < switch (netInfo.getType()) < case ConnectivityManager.TYPE_MOBILE: case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIMAX: return true; default: return false; >> return false; > private class NetworkConnectionStatusReceiver extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < if (hasConnection()) < // network available >else < // no network >; > > 

Источник

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