How to check internet access on Android? InetAddress never times out
JavaAndroidAndroid AsynctaskAndroid NetworkingJava Problem Overview
I got a AsyncTask
that is supposed to check the network access to a host name. But the doInBackground()
is never timed out. Anyone have a clue?
public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {
private Main main;
public HostAvailabilityTask(Main main) {
this.main = main;
}
protected Boolean doInBackground(String... params) {
Main.Log("doInBackground() isHostAvailable():"+params[0]);
try {
return InetAddress.getByName(params[0]).isReachable(30);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean... result) {
Main.Log("onPostExecute()");
if(result[0] == false) {
main.setContentView(R.layout.splash);
return;
}
main.continueAfterHostCheck();
}
}
Java Solutions
Solution 1 - Java
If the device is in airplane mode (or presumably in other situations where there's no available network), cm.getActiveNetworkInfo()
will be null
, so you need to add a null
check.
Modified (Eddie's solution) below:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
Also add the following permission to the AndroidManifest.xml
:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
One other small point, if you absolutely need a network connection at the given point in time, then it might be better to use netInfo.isConnected()
rather than netInfo.isConnectedOrConnecting
. I guess this is up to the individual use-case however.
Solution 2 - Java
Network connection / Internet access
isConnectedOrConnecting()
(used in most answers) checks for any network connection- To know whether any of those networks have internet access, use one of the following
A) Ping a Server (easy)
// ICMP
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
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(); }
return false;
}
+
could run on main thread
-
does not work on some old devices (Galays S3, etc.), it blocks a while if no internet is available.
B) Connect to a Socket on the Internet (advanced)
// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
public boolean isOnline() {
try {
int timeoutMs = 1500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) { return false; }
}
+
very fast (either way), works on all devices, very reliable
-
can't run on the UI thread
This works very reliably, on every device, and is very fast. It needs to run in a separate task though (e.g. ScheduledExecutorService
or AsyncTask
).
Possible Questions
-
Is it really fast enough?
Yes, very fast ;-)
-
Is there no reliable way to check internet, other than testing something on the internet?
Not as far as I know, but let me know, and I will edit my answer.
-
What if the DNS is down?
Google DNS (e.g.
8.8.8.8
) is the largest public DNS in the world. As of 2018 it handled over a trillion queries a day [1]. Let 's just say, your app would probably not be the talk of the day. -
Which permissions are required?
<uses-permission android:name="android.permission.INTERNET" />
Just internet access - surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about internet access, without this permission?)
RxJava/RxAndroid
Example (Kotlin)
Extra: One-shot fun hasInternetConnection(): Single<Boolean> {
return Single.fromCallable {
try {
// Connect to Google DNS to check for connection
val timeoutMs = 1500
val socket = Socket()
val socketAddress = InetSocketAddress("8.8.8.8", 53)
socket.connect(socketAddress, timeoutMs)
socket.close()
true
} catch (e: IOException) {
false
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
///////////////////////////////////////////////////////////////////////////////////
// Usage
hasInternetConnection().subscribe { hasInternet -> /* do something */}
RxJava/RxAndroid
Example (Java)
Extra: One-shot public static Single<Boolean> hasInternetConnection() {
return Single.fromCallable(() -> {
try {
// Connect to Google DNS to check for connection
int timeoutMs = 1500;
Socket socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress("8.8.8.8", 53);
socket.connect(socketAddress, timeoutMs);
socket.close();
return true;
} catch (IOException e) {
return false;
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
///////////////////////////////////////////////////////////////////////////////////
// Usage
hasInternetConnection().subscribe((hasInternet) -> {
if(hasInternet) {
}else {
}
});
AsyncTask
Example
Extra: One-shot Caution: This shows another example of how to do the request. However, since AsyncTask
is deprecated, it should be replaced by your App's thread scheduling, Kotlin Coroutines, Rx, ...
class InternetCheck extends AsyncTask<Void,Void,Boolean> {
private Consumer mConsumer;
public interface Consumer { void accept(Boolean internet); }
public InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }
@Override protected Boolean doInBackground(Void... voids) { try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
return true;
} catch (IOException e) { return false; } }
@Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
}
///////////////////////////////////////////////////////////////////////////////////
// Usage
new InternetCheck(internet -> { /* do something with boolean response */ });
Solution 3 - Java
No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE
permission and just make a connected method
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
You can also use requestRouteToHost
if you have a particualr host and connection type (wifi/mobile) in mind.
You will also need:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your android manifest.
Solution 4 - Java
To get getActiveNetworkInfo()
to work you need to add the following to the manifest.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Solution 5 - Java
Take a look at the ConnectivityManager class. You can use this class to get information on the active connections on a host. http://developer.android.com/reference/android/net/ConnectivityManager.html
EDIT: You can use
Context.getSystemService(Context.CONNECTIVITY_SERVICE)
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
or
Context.getSystemService(Context.CONNECTIVITY_SERVICE)
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
and parse the DetailedState enum of the returned NetworkInfo object
EDIT EDIT: To find out whether you can access a host, you can use
Context.getSystemService(Context.CONNECTIVITY_SERVICE)
.requestRouteToHost(TYPE_WIFI, int hostAddress)
Obviously, I'm using Context.getSystemService(Context.CONNECTIVITY_SERVICE) as a proxy to say
ConnectivityManager cm = Context.getSystemService(Context.CONNECTIVITY_SERVICE);
cm.yourMethodCallHere();
Solution 6 - Java
check this code... it worked for me :)
public static void isNetworkAvailable(final Handler handler, final int timeout) {
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in milliseconds)
new Thread() {
private boolean responded = false;
@Override
public void run() {
// set 'responded' to TRUE if is able to connect with google mobile (responds fast)
new Thread() {
@Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
}
catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0); }
else { handler.sendEmptyMessage(1); }
}
}
}.start();
}
Then, I define the handler:
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
...and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
Solution 7 - Java
Found at and modified (!) from this link :
In your manifest file add at least:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You probably already have the INTERNET permission if you are accessing it. Then a boolean function that allows to test for connectivity is:
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 {
Log.v(TAG, "Internet Connection Not Present");
return false;
}
}
Solution 8 - Java
I made this code, it is the simplest and it is just a boolean.
by asking if(isOnline()){
You get if there is a connection and if it can connect to a page the status code 200
(stable connection).
Make sure to add the correct INTERNET
and ACCESS_NETWORK_STATE
permissions.
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return new Boolean(true);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
Solution 9 - Java
It does works for me:
To verify network availability:
private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();}
To verify internet access:
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
Solution 10 - Java
There's more than one way
First, shortest but Inefficient way
Network State Permission only needed
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then this method,
public boolean activeNetwork () {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
As seen in answers ConnectivityManager
is a solution, I just added it within a method this is a simplified method all use
ConnectivityManager
returns true if there is a network access not Internet access, means if your WiFi is connected to a router but the router has no internet it returns true, it check connection availability
Second, Efficient way
Network State and Internet Permissions needed
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Then this class,
public class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private Context context;
public CheckInternetAsyncTask(Context context) {
this.context = context;
}
@Override
protected Boolean doInBackground(Void... params) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
if (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0)
return true;
} catch (IOException e) {
Log.e("TAG", "Error checking internet connection", e);
return false;
}
} else {
Log.d("TAG", "No network available!");
return false;
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TAG", "result" + result);
if(result){
// do ur code
}
}
}
Call CheckInternetAsyncTask
new CheckInternetAsyncTask(getApplicationContext()).execute();
Some Explanations :-
-
you have to check Internet on
AsyncTask
, otherwise it can throwandroid.os.NetworkOnMainThreadException
in some cases -
ConnectivityManager
used to check the network access if true sends request (Ping) -
Request send to
http://clients3.google.com/generate_204
, This well-known URL is known to return an empty page with an HTTP status 204 this is faster and more efficient thanhttp://www.google.com
, read this. if you have website it's preferred to put you website instead of google, only if you use it within the app -
Timeout can be changed range (20ms -> 2000ms), 1500ms is commonly used
Solution 11 - Java
Here is the method I use:
public boolean isNetworkAvailable(final Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
Even better, check to make sure it is "connected":
public boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Here is how to use the method:
if (isNetworkAvailable(context)) {
// code here
} else {
// code
}
Permission needed:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Solution 12 - Java
Of everything I have seen so far shortest and cleanest way should be:
public final static boolean isConnected( Context context )
{
final ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
PS: This does not ping any host, it just checks the connectionstatus, so if your router has no internet connection and your device is connected to it this method would return true although you have no internet.
For an actual test I would recommend execuding a HttpHead request (e.g. to www.google.com) and check the status, if its 200 OK everything is fine and your device has an internet connection.
Solution 13 - Java
One important use case on mobile devices to it ensure an actual connection exists. This is a common problem when a mobile user enters a Wifi network with a "Captive Portal", in which they need to sign in. I use this blocking function in the background to ensure a connection exists.
/*
* Not Thread safe. Blocking thread. Returns true if it
* can connect to URL, false and exception is logged.
*/
public boolean checkConnectionHttps(String url){
boolean responded = false;
HttpGet requestTest = new HttpGet(url);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 5000);
DefaultHttpClient client = new DefaultHttpClient(params);
try {
client.execute(requestTest);
responded = true;
} catch (ClientProtocolException e) {
Log.w(MainActivity.TAG,"Unable to connect to " + url + " " + e.toString());
} catch (IOException e) {
Log.w(MainActivity.TAG,"Unable to connect to " + url + " " + e.toString());
e.printStackTrace();
}
return responded;
}
Solution 14 - Java
Kotlin and coroutines
I have placed the function in a ViewModel
, which has the viewModelScope
. Using an observable LiveData
I inform an activity about the connection.
ViewModel
fun checkInternetConnection(timeoutMs: Int) {
viewModelScope.launch(Dispatchers.IO) {
try {
val socket = Socket()
val socketAddress = InetSocketAddress("8.8.8.8", 53)
socket.connect(socketAddress, timeoutMs)
socket.close()
_connection.postValue(true)
}
catch(ex: IOException) {
_connection.postValue(false)
}
}
}
private val _connection = MutableLiveData<Boolean>()
val connection: LiveData<Boolean> = _connection
Activity
private fun checkInternetConnection() {
viewModel.connection.observe(this) { hasInternet ->
if(!hasInternet) {
//hasn't connection
}
else {
//has connection
}
}
}
Solution 15 - Java
Im using this code instead of the InetAddress :
try {
URL url = new URL("http://"+params[0]);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Main.Log("getResponseCode == 200");
return new Boolean(true);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Solution 16 - Java
You can iterate over all network connections and chek whether there is at least one available connection:
public boolean isConnected() {
boolean connected = false;
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI")
|| ni.getTypeName().equalsIgnoreCase("MOBILE"))
&& ni.isConnected() && ni.isAvailable()) {
connected = true;
}
}
}
return connected;
}
Solution 17 - Java
It's works for me. Try it out.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
URL url = new URL("http://stackoverflow.com/posts/11642475/edit" );
//URL url = new URL("http://www.nofoundwebsite.com/" );
executeReq(url);
Toast.makeText(getApplicationContext(), "Webpage is available!", Toast.LENGTH_SHORT).show();
}
catch(Exception e) {
Toast.makeText(getApplicationContext(), "oops! webpage is not available!", Toast.LENGTH_SHORT).show();
}
}
private void executeReq(URL urlObject) throws IOException
{
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlObject.openConnection();
conn.setReadTimeout(30000);//milliseconds
conn.setConnectTimeout(3500);//milliseconds
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Start connect
conn.connect();
InputStream response =conn.getInputStream();
Log.d("Response:", response.toString());
}}
Solution 18 - Java
For me it was not a good practice to check the connection state in the Activity class, because
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
should be called there, or you need to push down your Activity instance (context) to the connection handler class to able to check the connection state there When no available connection (wifi, network) I catch the UnknownHostException exception:
JSONObject jObj = null;
Boolean responded = false;
HttpGet requestForTest = new HttpGet("http://myserver.com");
try {
new DefaultHttpClient().execute(requestForTest);
responded = true;
} catch (UnknownHostException e) {
jObj = new JSONObject();
try {
jObj.put("answer_code", 1);
jObj.put("answer_text", "No available connection");
} catch (Exception e1) {}
return jObj;
} catch (IOException e) {
e.printStackTrace();
}
In this way I can handle this case along with the other cases in the same class (my server always response back with a json string)
Solution 19 - Java
This method gives you the option for a really fast method (for real time feedback) or a slower method (for one off checks that require reliability)
public boolean isNetworkAvailable(bool SlowButMoreReliable) {
bool Result = false;
try {
if(SlowButMoreReliable){
ConnectivityManager MyConnectivityManager = null;
MyConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo MyNetworkInfo = null;
MyNetworkInfo = MyConnectivityManager.getActiveNetworkInfo();
Result = MyNetworkInfo != null && MyNetworkInfo.isConnected();
} else
{
Runtime runtime = Runtime.getRuntime();
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int i = ipProcess.waitFor();
Result = i== 0;
}
} catch(Exception ex)
{
//Common.Exception(ex); //This method is one you should have that displays exceptions in your log
}
return Result;
}
Solution 20 - Java
You can use this method to detect network availability-
public static boolean isDeviceOnline(Context context) {
boolean isConnectionAvail = false;
try {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo.isConnected();
} catch (Exception e) {
e.printStackTrace();
}
return isConnectionAvail;
}
Solution 21 - Java
It is not complex to check Android network / internet connectivity status. The below DetectConnection
class will help you to check this status:
import android.content.Context;
import android.net.ConnectivityManager;
public class DetectConnection {
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
}
For more details visit How to Check Android Network / Internet Connectivity Status
Solution 22 - Java
Best approach:
public static boolean isOnline() {
try {
InetAddress.getByName("google.com").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
Solution 23 - Java
Following is the code from my Utils
class:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Solution 24 - Java
public class Network {
Context context;
public Network(Context context){
this.context = context;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
Solution 25 - Java
This is covered in android docs http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
Solution 26 - Java
Very important to check if we have connectivity with isAvailable() and if is possible to establish a connection with isConnected()
private static ConnectivityManager manager;
public static boolean isOnline(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}
and you can derterminate the type of network active WiFi :
public static boolean isConnectedWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
or mobile Móvil :
public static boolean isConnectedMobile(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
don´t forget the permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Solution 27 - Java
I have applied the solution provided by @Levit and created function that will not call the extra Http Request.
It will solve the error Unable to Resolve Host
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) return false;
switch (activeNetwork.getType()) {
case ConnectivityManager.TYPE_WIFI:
if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
isInternet())
return true;
break;
case ConnectivityManager.TYPE_MOBILE:
if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
isInternet())
return true;
break;
default:
return false;
}
return false;
}
private static boolean isInternet() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
Debug.i(exitValue + "");
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
Now call it like,
if (!isInternetAvailable(getActivity())) {
//Show message
} else {
//Perfoem the api request
}
Solution 28 - Java
Update 29/06/2015 If you are using Xamarin.Android and want to check for connectivity, you can use a Nuget package that would give you this functionality on multiple platforms. Good candidates are here and here. [End of Update]
The Answers above are quite good, but they are all in Java, and almost all of them check for a connectivity. In my case, I needed to have connectivity with a specific type of connection and I am developing on Xamarin.Android. Moreover, I do not pass a reference to my activities Context in the Hardware layer, I use the Application Context. So here is my solution, in case somebody comes here with similar requirements. I have not done full testing though, will update the answer once I am done with my testing
using Android.App;
using Android.Content;
using Android.Net;
namespace Leopard.Mobile.Hal.Android
{
public class AndroidNetworkHelper
{
public static AndroidNetworkStatus GetWifiConnectivityStatus()
{
return GetConnectivityStatus(ConnectivityType.Wifi);
}
public static AndroidNetworkStatus GetMobileConnectivityStatus()
{
return GetConnectivityStatus(ConnectivityType.Mobile);
}
#region Implementation
private static AndroidNetworkStatus GetConnectivityStatus(ConnectivityType connectivityType)
{
var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
var wifiNetworkInfo = connectivityManager.GetNetworkInfo(connectivityType);
var result = GetNetworkStatus(wifiNetworkInfo);
return result;
}
private static AndroidNetworkStatus GetNetworkStatus(NetworkInfo wifiNetworkInfo)
{
var result = AndroidNetworkStatus.Unknown;
if (wifiNetworkInfo != null)
{
if (wifiNetworkInfo.IsAvailable && wifiNetworkInfo.IsConnected)
{
result = AndroidNetworkStatus.Connected;
}
else
{
result = AndroidNetworkStatus.Disconnected;
}
}
return result;
}
#endregion
}
public enum AndroidNetworkStatus
{
Connected,
Disconnected,
Unknown
}
Solution 29 - Java
The other answers that use ConnectivityManager are wrong because having a network connection doesn't mean you have internet access. For example, the user might be connected to a coffee shop's WiFi portal but can't get to the internet. To check that the internet is accessible you have to try to connect to an actual server. Normally when you want to do this you have a specific server in mind that you want to connect to, so go ahead and check if you can connect to that server. Here's a simple method for checking connectivity to a server.
private boolean isOnTheInternet() {
try {
URLConnection urlConnection = new URL("http://yourserver").openConnection();
urlConnection.setConnectTimeout(400);
urlConnection.connect();
return true;
} catch (Exception e) {
return false;
}
}
The reason for setting the ConnectTimeout is that otherwise it defaults to the TCP timeout which can be many seconds long.
Note also that Android won't let you run this on your main thread.
Solution 30 - Java
I have gone through all the answers and i come up with my own answer which first check whether Internet is available and if Internet is available then it check whether it is active or not.
I have included all necessary method and classes to check for active Internet connection.
NetworkUtils.class
public class NetworkUtils {
public static final int STATUS_CONNECTED = 0 ;
public static boolean isInternetAvailable(Context ctx){
ConnectivityManager cm = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public static int isInternetActiveWithPing() {
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = process.waitFor();
return exitValue;
} catch (Exception ex) {
return -1;
}
}
public static boolean isInternetActiveWithInetAddress() {
try {
InetAddress inetAddress = InetAddress.getByName("www.google.com");
return inetAddress != null && !inetAddress.toString().equals("");
} catch (Exception ex) {
return false;
}
}
public static void displayInternetConnectionMessage(Context ctx){
Toast.makeText(ctx, "Check Internet Connection", Toast.LENGTH_SHORT).show();
}
}
You can check whether Internet is active using below code:
private void checkInternetConnection() {
if (NetworkUtils.isInternetAvailable(this)) {
new Thread(new Runnable() {
@Override
public void run() {
if (NetworkUtils.isInternetActiveWithPing() == NetworkUtils.STATUS_CONNECTED) {
performNetworkingOperations();
} else {
if (NetworkUtils.isInternetActiveWithInetAddress()) {
performNetworkingOperations();
} else {
displayConnectionMessage();
}
}
}
}).start();
} else {
displayConnectionMessage();
}
}
private void performNetworkingOperations() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Internet is Available", Toast.LENGTH_SHORT).show();
}
});
}
private void displayConnectionMessage() {
runOnUiThread(new Runnable() {
@Override
public void run() {
NetworkUtils.displayInternetConnectionMessage(MainActivity.this);
}
});
}
Solution 31 - Java
Just create the following class which checks for an internet connection:
public class ConnectionStatus {
private Context _context;
public ConnectionStatus(Context context) {
this._context = context;
}
public boolean isConnectionAvailable() {
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;
}
}
This class simply contains a method which returns the boolean value of the connection status. Therefore in simple terms, if the method finds a valid connection to the Internet, the return value is true
, otherwise false
if no valid connection is found.
The following method in the MainActivity then calls the result from the method previously described, and prompts the user to act accordingly:
public void addListenerOnWifiButton() {
Button btnWifi = (Button)findViewById(R.id.btnWifi);
iia = new ConnectionStatus(getApplicationContext());
isConnected = iia.isConnectionAvailable();
if (!isConnected) {
btnWifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
Toast.makeText(getBaseContext(), "Please connect to a hotspot",
Toast.LENGTH_SHORT).show();
}
});
}
else {
btnWifi.setVisibility(4);
warning.setText("This app may use your mobile data to update events and get their details.");
}
}
In the above code, if the result is false, (therefore there is no internet connection, the user is taken to the Android wi-fi panel, where he is prompted to connect to a wi-fi hotspot.
Solution 32 - Java
If you are using API 23 or above, you can now check whether or not internet is active using NetworkCapabilities.NET_CAPABILITY_VALIDATED, which is backed by Google's own ping service.
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onLost(Network network) {
// handle network lost
}
@Override
public void onAvailable(Network network) {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getNetworkInfo(network);
boolean isConnected = (info != null && info.isConnectedOrConnecting());
if (isConnected) {
NetworkCapabilities nc = cm.getNetworkCapabilities(network);
if (nc != null) {
boolean isInternetValid = nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
if (isInternetValid) {
// internet is valid
}
}
}
}
};
NetworkRequest request = new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(request, networkCallback);
Solution 33 - Java
The most Simplest solution would be
In most cases one will only check internet connection if he/she wants to connect to the remote server so the simple and best solution would be pinging your server as following.
public boolean isConnected() {
final String command = "ping -c 1 yourExmapleDomain.com";
boolean isConnected = false;
try {
isConnected = Runtime.getRuntime().exec(command).waitFor() == 0;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isConnected;
}
Solution 34 - Java
Use this Kotlin Extension:
/**
* Check whether network is available
*
* @param context
* @return Whether device is connected to Network.
*/
fun Context.isNetworkAvailable(): Boolean {
with(getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//Device is running on Marshmallow or later Android OS.
with(getNetworkCapabilities(activeNetwork)) {
return hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || hasTransport(
NetworkCapabilities.TRANSPORT_CELLULAR
)
}
} else {
activeNetworkInfo?.let {
// connected to the internet
@Suppress("DEPRECATION")
return listOf(ConnectivityManager.TYPE_WIFI, ConnectivityManager.TYPE_MOBILE).contains(it.type)
}
}
}
return false
}
Solution 35 - Java
public boolean isOnline() {
boolean var = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if ( cm.getActiveNetworkInfo() != null ) {
var = true;
}
return var;
}
I have done it this way. A little bit shorter and more readable I guess.
Cheers!
Saiyan
Solution 36 - Java
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager connMgr = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected() ||
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()){
return true;
}
return false;
}
user this
Solution 37 - Java
Its so great to have more then one way to code. Here is my example.
ConnectivityManager icheck = getSystemService(Context.CONNECTIVITY_SERVICE);
TextView tv = findViewById(R.id.textView1);
boolean wifi = icheck.getActiveNetworkInfo() != null;
if(wifi) {
tv.setText("Internet is on.");
} else {
tv.setText("Internet is off.");
}
Good luck.
Solution 38 - Java
I have tried with almost 5+ different android approaches and found this is the best solution provided by google especially for android:
try {
HttpURLConnection urlConnection = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlConnection.setRequestProperty("User-Agent", "Android");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(1500);
urlConnection.connect();
if (urlConnection.getResponseCode() == 204 &&
urlConnection.getContentLength() == 0) {
Log.d("Network Checker", "Successfully connected to internet");
return true;
}
} catch (IOException e) {
Log.e("Network Checker", "Error checking internet connection", e);
}
It's faster
, efficient
and accurate
than any other available solution.
Solution 39 - Java
This code will help you find the internet is on or not.
public final boolean isInternetOn() {
ConnectivityManager conMgr = (ConnectivityManager) this.con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conMgr.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
Also, you should provide the following permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Solution 40 - Java
If you need to check for the internet connection, use this method using ping to the server:
public boolean checkIntCON() {
try {
Process ipProcess = Runtime.getRuntime().exec("/system/bin/ping -c 1 8.8.8.8");
return (ipProcess.waitFor() == 0);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
Either you can use check through using port
public boolean checkIntCON() {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 80);
// port will change according to protocols
sock.connect(sockaddr, 1250);
sock.close();
return true;
} catch (IOException e) { return false; }
}
Solution 41 - Java
This is simplest and easy way to check internet connection for wifi and mobile data.
public static boolean isConnected(Activity _context) {
if (_context != null) {
ConnectivityManager connMgr = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
boolean wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
boolean mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if (wifiConnected || mobileConnected) {
Log.d(TAG, "Wifi Connected ");
return true;
} else {
showAlert(_context,_context.getString(R.string.err_no_internet));
return false;
}
} else {
showAlert(_context,_context.getString(R.string.err_no_internet));
return false;
}
} else {
Log.e(TAG, "networkConnectivity: Context NULL");
}
return false;
}
Solution 42 - Java
public static boolean isNetworkAvailable(Context context) {
boolean flag = checkNetworkAvailable(context);
if (!flag) {
Log.d("", "No network available!");
}
return flag;
}
private static boolean checkNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
Solution 43 - Java
As Android doc suggest, after > getActiveNetworkInfo() was deprecated in Android 10. Use > NetworkCallbacks instead for apps that target Android 10 (API level > 29) and higher.
So below is the way which we are using to check network connection Currently:
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val isConnected: Boolean = activeNetwork?.isConnectedOrConnecting == true
The new way for checking internet connection using NetworkCallbacks
Step 1:
private lateinit var connectivityManager:ConnectivityManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
}
Step 2: Create Callback:
private val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
Timber.e("Network:onAvailable")
}
override fun onLost(network: Network) {
super.onLost(network)
Timber.e("Network:onLost")
}
}
Step 3: Register and UnRegister CallBack:
private fun registerNetworkCallback() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(callback)
} else {
// Old way to check network connection
}
}
override fun onStop() {
unRegisterNetworkCallback()
super.onStop()
}
private fun unRegisterNetworkCallback() {
connectivityManager.unregisterNetworkCallback(callback)
}
Checkout update details on below link:
https://developer.android.com/training/monitoring-device-state/connectivity-status-type
Solution 44 - Java
Use method:
private fun isInternetAvailable(context: Context): Boolean {
(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).run {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return this.getNetworkCapabilities(this.activeNetwork)?.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET
) ?: false
} else {
(@Suppress("DEPRECATION")
return this.activeNetworkInfo?.isConnected ?: false)
}
}
}
And permissions required:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Solution 45 - Java
Kotlin implementation
/**
* Function that uses ping, takes server name or ip as argument.
*
* @return [Double.MAX_VALUE] if server is not reachable. Average RTT if the server is reachable.
*
* Success output example
*
* PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
* 64 bytes from 8.8.8.8: icmp_seq=1 ttl=254 time=172 ms
* 64 bytes from 8.8.8.8: icmp_seq=2 ttl=254 time=166 ms
* 64 bytes from 8.8.8.8: icmp_seq=3 ttl=254 time=167 ms
* 64 bytes from 8.8.8.8: icmp_seq=4 ttl=254 time=172 ms
* 64 bytes from 8.8.8.8: icmp_seq=5 ttl=254 time=167 ms
* --- 8.8.8.8 ping statistics ---
* 5 packets transmitted, 5 received, 0% packet loss, time 4011ms
* rtt min/avg/max/mdev = 166.470/169.313/172.322/2.539 ms
* |________________________|
* value to parse using it.split('=')[1].trim().split(' ')[0].trim().split('/')[1].toDouble()
*/
@ExperimentalStdlibApi
fun pingServerAverageRtt(host: String): Double {
var aveRtt: Double = Double.MAX_VALUE
try {
// execute the command on the environment interface, timeout is set as 0.2 to get response faster.
val pingProcess: Process = Runtime.getRuntime().exec("/system/bin/ping -i 0.2 -c 5 $host")
// gets the input stream to get the output of the executed command
val bufferedReader = BufferedReader(InputStreamReader(pingProcess.inputStream))
bufferedReader.forEachLine {
if (it.isNotEmpty() && it.contains("min/avg/max/mdev")) { // when we get to the last line of executed ping command
aveRtt = it.split('=')[1].trim()
.split(' ')[0].trim()
.split('/')[1].toDouble()
}
}
} catch (e: IOException) {
e.printStackTrace()
}
return aveRtt
}
Usage example
val latency = pingServerAverageRtt(ipString)
if (latency != Double.MAX_VALUE) {
//server reachable
} else {
//server not reachable
}
Solution 46 - Java
If you're using Firebase you could use this.
Java:
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
Log.d(TAG, "connected");
} else {
Log.d(TAG, "not connected");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.w(TAG, "Listener was cancelled");
}
});
Kotlin:
val connectedRef = Firebase.database.getReference(".info/connected")
connectedRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val connected = snapshot.getValue(Boolean::class.java) ?: false
if (connected) {
Log.d(TAG, "connected")
} else {
Log.d(TAG, "not connected")
}
}
override fun onCancelled(error: DatabaseError) {
Log.w(TAG, "Listener was cancelled")
}
})
Solution 47 - Java
if(isConnected()){
Toast.makeText(getApplication(),"Thank you",Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder builder =
new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("Amar Bhat");
builder.setMessage("Oops...You are not connected to Internet!!!");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();
//Toast.makeText(getApplication(),"You are not connected",Toast.LENGTH_SHORT).show();
}
//And outside the class define isConnected()
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
// In minifest add these permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Solution 48 - Java
Don't forget to add this permissions to your manifest :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Solution 49 - Java
Most of the answers in this thread only check if there is a connection available but do not check if that connection work, others answers are not device wide, my solution should work on every device.
You can drop my code in your main activity before launching the app, it will quickly determine if there is an actual internet connectivity, if there is the dialog will be immediately dropped and the app will be launched, if not an alert will pop up saying the app needs internet connectivity to work.
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Checking Connection");
alertDialog.setMessage("Checking...");
alertDialog.show();
new CountDownTimer(5000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL("http://web.mit.edu/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
isConnected = connection.getResponseCode() == HttpURLConnection.HTTP_OK;
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
if (isConnected == false){
alertDialog.setMessage("Try " + (5 - millisUntilFinished/1000) + " of 5.");
} else {
alertDialog.dismiss();
}
}
@Override
public void onFinish() {
if (isConnected == false) {
alertDialog.dismiss();
new AlertDialog.Builder(activity)
.setTitle("No Internet")
.setMessage("Please connect to Internet first.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// kill the app?
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
} else {
// Launch the app
}
}
}.start();
Solution 50 - Java
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Here is the permission that you need :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Solution 51 - Java
You can check internet with below code as well:
public class CheckInternetConnection {
public Context context = null;
public CheckInternetConnection(Context ctx) {
this.context = ctx;
}
public boolean CheckInternet() {
return isOnline();
}
public Boolean isOnline()
{
try {
if(isNetAvailable(context))
return true;
else
{
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(3000); // This is time limit if the
// connection time limit
try {
urlc.connect();
Log.e("TAG", " urlc ----------" + urlc.getResponseCode());
if (urlc.getResponseCode() == 200) {
return true;
}
}catch (Exception e){
e.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
public synchronized static boolean isNetAvailable(Context context){
try{
boolean isNetAvailable=false;
if ( context != null )
{
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if ( mgr != null )
{
boolean mobileNetwork = false;
boolean wifiNetwork = false;
boolean wiMaxNetwork = false;
boolean mobileNetworkConnecetd = false;
boolean wifiNetworkConnecetd = false;
boolean wiMaxNetworkConnected = false;
NetworkInfo mobileInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo wiMaxInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
if ( mobileInfo != null )
mobileNetwork = mobileInfo.isAvailable();
if ( wifiInfo != null )
wifiNetwork = wifiInfo.isAvailable();
if(wiMaxInfo != null)
wiMaxNetwork = wiMaxInfo.isAvailable();
if(wifiNetwork == true)
wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
if(mobileNetwork == true)
mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting();
if(wiMaxNetwork == true)
wiMaxNetworkConnected = wiMaxInfo.isConnectedOrConnecting();
isNetAvailable = ( mobileNetworkConnecetd || wifiNetworkConnecetd || wiMaxNetworkConnected );
}
}
return isNetAvailable;
}catch(NullPointerException e)
{
return false;
}catch(Exception e)
{
return false;
}
}
}
Solution 52 - Java
Here is some modern code that uses an AsynTask
to get around an issue where android crashes when you try and connect on the main thread and introduces an alert with a rinse and repeat option for the user.
class TestInternet extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
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();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("An internet connection is required.");
builder.setCancelable(false);
builder.setPositiveButton(
"TRY AGAIN",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new TestInternet().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
doMyStuff();
}
}
}
...
new TestInternet().execute();
Solution 53 - Java
Instead of checking WIFI connection or Mobile data connection, try hitting any hosted domain. So that, you can check whether the WIFI/Mobile connection has ability to connect public Internet.
The below will return if your mobile device is able to connect with the public domain provided.
boolean isReachable()
{
boolean connected = false;
String instanceURL = "Your trusted domain name";
Socket socket;
try {
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(instanceURL, 80);
socket.connect(socketAddress, 5000);
if (socket.isConnected()) {
connected = true;
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
socket = null;
}
return connected;
}
Hope it will be helpful..
Solution 54 - Java
Android provides ConnectivityManager class to know about the internet connection status. The following method will be very useful to know internet connection state.
First add the INTERNET and ACCESS_NETWORK_STATE permission to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then use the below method to check if the device is connected to internet or not. This method will return true if the device is connected to internet.
public boolean isInternetAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
}
Reference Link :- http://www.androidtutorialshub.com/android-check-internet-connection-status/
Solution 55 - Java
Here is the optimal method for checking internet connection. What this method does is perform a series of checks "is the phone not in airplane mode, is the phone connected to a network, etc". If all the checks return true, the method will then download a file from the internet and see if the contents matches an expected value.
The benefits of this method compared to other methods that ping a server to check for internet connection are:
-
The Android runtime varies on different phones - so you may not always be able to execute those commands, as shown here: https://stackoverflow.com/questions/32749462/why-does-ping-works-on-some-devices-and-not-others
-
Pinging a server doesn't always work because of login pages/re-directs on wifi networks which can give the false impression of a connection.
This answer is written in Kotlin and uses the Fuel library to download a file from the internet with the methodfetchUrlAsString
, but any library can be substituted as long as you make sure your HTTP request is not cached. Think of showConnectionWarning()
and hideConnectionWarning()
as equivalent to internet connection status = false
and internet connection status = true
respectively.
private val networkReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val activeNetworkInfo = (context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
if (activeNetworkInfo != null) {
if (activeNetworkInfo.isConnectedOrConnecting) {
//Launches a coroutine to fetch file asynchronously
launch {
try {
//Downloads file from url on the internet - use any library you want here.
val connectionStatus = fetchUrlAsString(<url_for_file_on_internet>)
//check if the contents of the file is as expected
if (connectionStatus == "Connected To Database") {
hideConnectionWarning()
} else {
showConnectionWarning()
}
} catch (e: Exception) {
//Catches an exception - fetchUrlAsString only throws an exception if there is no internet
showConnectionWarning()
}
}
} else {
showConnectionWarning()
}
} else {
showConnectionWarning()
}
}
}
private suspend fun fetchUrlAsString(url: String): String = suspendCoroutine { cont ->
url.httpGet().header(Pair("pragma", "no-cache"), Pair("cache-control", "no-cache")).responseString { _, _, result ->
when (result) {
is Result.Failure -> {
cont.resumeWithException(result.getException())
}
is Result.Success -> {
cont.resume(result.value)
}
}
}
}
You will need the following permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Solution 56 - Java
Here is the Kotlin version I use for reachability checking,
###Kotlin MyReachability object MyReachability {
private val REACHABILITY_SERVER = "http://google.com" // can be any URL you want
private fun hasNetworkAvailable(context: Context): Boolean {
val service = Context.CONNECTIVITY_SERVICE
val manager = context.getSystemService(service) as ConnectivityManager?
val network = manager?.activeNetworkInfo
Log.d(classTag, "hasNetworkAvailable: ${(network != null)}")
return (network != null)
}
fun hasInternetConnected(context: Context): Boolean {
if (hasNetworkAvailable(context)) {
try {
val connection = URL(REACHABILITY_SERVER).openConnection() as HttpURLConnection
connection.setRequestProperty("User-Agent", "Test")
connection.setRequestProperty("Connection", "close")
connection.connectTimeout = 1500
connection.connect()
Log.d(classTag, "hasInternetConnected: ${(connection.responseCode == 200)}")
return (connection.responseCode == 200)
} catch (e: IOException) {
Log.e(classTag, "Error checking internet connection", e)
}
} else {
Log.w(classTag, "No network available!")
}
Log.d(classTag, "hasInternetConnected: false")
return false
}
}
You can even pass the REACHABILITY_SERVER
as param based on policy and restrictions, for example when you are in china you can check https://baidu.com rather https://google.com.
###Calling example,
val webLoaderThread = Thread {
if (MyReachability.hasInternetConnected(this)){
runOnUiThread {
//mWebView.loadUrl(LANDING_SERVER) // connected
}
} else {
runOnUiThread {
//showDialogNoNetwork() // not connected
}
}
}
webLoaderThread.start()
###Android permissions
Dont forget to add these below permissions to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Solution 57 - Java
Using the following method to check internet connectivity, also ConnectivityManager.getActiveNetworkInfo() is deprecated in API 28
@Suppress("DEPRECATION")
fun isNetworkConnected(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return cm?.run {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
when {
hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
} else {
cm.activeNetworkInfo?.run {
when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
else -> false
}
}
}
} ?: false
}
Also add the following permission to the manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) is used for apps developed for Android TV where TV can be directly connected to Ethernet
Solution 58 - Java
This my workaround to solve this problem and check the valid internet connection because as they said that Network info class cannot give you the expected result and it may return true when network connected but no internet.
So this my COMPLETE WORKAROUND based on @Levite Answer:
First you must have AsynckTask for checking Network availability and this is mine:
public class Connectivity {
private static final String TAG = "Connectivity";
private static boolean hasConnected = false, hasChecked = false;
private InternetListener internetListener;
private Activity activity;
public Connectivity(InternetListener internetListener, Activity activity) {
this.internetListener = internetListener;
this.activity = activity;
}
public void startInternetListener() {
CheckURL checkURL = new CheckURL(activity);
checkURL.execute();
long startTime = System.currentTimeMillis();
while (true) {
if (hasChecked && hasConnected) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onConnected();
}
});
checkURL.cancel(true);
return;
}
// check if time
if (System.currentTimeMillis() - startTime >= 1000) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onDisconnected();
}
});
checkURL.cancel(true);
return;
}
}
//return hasConnected;
}
class CheckURL extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
public CheckURL(Activity activity) {
this.activity = activity;
}
@Override
protected Boolean doInBackground(Void... params) {
if (!isNetWorkAvailable(activity)) {
Log.i(TAG, "Internet not available!");
return false;
}
int timeoutMs = 3000;
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
Log.i(TAG, "Internet available :)");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
hasChecked = true;
hasConnected = result;
super.onPostExecute(result);}}
private static final String TAG = "Connectivity";
private static boolean isNetWorkAvailable(Activity activity) {
ConnectivityManager connectivityManager =
(ConnectivityManager)
activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);}
}}
private static boolean isNetWorkAvailable(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);
}
}
After that you should create another thread to start AscnkTask And listen for result with the InternetListener.
public interface InternetListener {
void onConnected();
void onDisconnected();
}
And the Thread that is waiting for AsynckTask result you can put it in Utility class:
private static Thread thread;
public static void startNetworkListener(Context context, InternetListener
internetListener) {
if (thread == null){
thread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
new Connectivity(internetListener,context).startInternetListener();
}
});
}
thread.start();
}
Finally call the startNetworkListener() method and listen for result.
example in activity from My Utils.java class :
Utils.startNetworkListener(this, new InternetListener() {
@Override
public void onConnected() {
// do your work when internet available.
}
@Override
public void onDisconnected() {
// do your work when no internet available.
}
});
Happy Coding :).
Solution 59 - Java
If you want to show an alert when connection lost. You can use below method.
This method use to check connection one time. First you have to create this one in your class.
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected())){
showNetworkDialog();
return false;
}
return true;
}
Create this method in your class as connection listener.
private void ConnectionCheck(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest networkRequest = new NetworkRequest.Builder().build();
connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
Log.i("Tag", "active connection");
}
@Override
public void onLost(Network network) {
super.onLost(network);
Log.i("Tag", "losing active connection");
isNetworkConnected();
}
});
}
}
For showing dialog, you may create showDialog() method.
private void showNetworkDialog(){
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Connection lost?")
.setMessage("Please check your internet connection!")
.setCancelable(false)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
isNetworkConnected();
}
})
.show();
}
Finally you can call this method in onCreate() method.
if(isNetworkConnected()){
ConnectionCheck();
}
in Manifest file you have to mention permission.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Solution 60 - Java
Code :
fun isInternetConnection(): Boolean {
var returnVal = false
thread {
returnVal = try {
khttp.get("https://www.google.com/")
true
}catch (e:Exception){
false
}
}.join()
return returnVal
}
Gradle:
implementation 'io.karn:khttp-android:0.1.0'
I use khttp because it's so easy to use.
So here in the above code if it successfully connects to google.com, it returns true else false. It's so simple. I don't understand why everyone has to code like lengthy lines of code even for a simple thing like this.
Solution 61 - Java
In kotlin:
class UtilityMethods {
companion object {
fun isConnected(activity: Activity): Boolean {
val connectivityManager: ConnectivityManager =
activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return null != connectivityManager.activeNetworkInfo
}
}}
Invoke isConnected inside Activity class as:
UtilityMethods.isConnected(this)
Inside fragment class as:
UtilityMethods.isConnected(activity)