How to test for active internet connection in android
Follow below code to check properly Internet is available or not as well as active or not.
//I have taken dummy icon from server, so it may be removed in future. So you can place one small icon on server and then access your own URL.
1. Specify Permission in manifest file, also make sure for marshmellwo runtime permission handle. As I am not going to show reuntime permission here.
<uses-permission android:name="android.permission.INTERNET"/>
2. Check for Internet Availibility and the State as Active or Inactive.
public class InternetDemo extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkInternetAvailibility();
}
public void checkInternetAvailibility()
{
if(isInternetAvailable())
{
new IsInternetActive().execute();
}
else {
Toast.makeText(getApplicationContext(), "Internet Not Connected", Toast.LENGTH_LONG).show();
}
}
public boolean isInternetAvailable() {
try {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
} catch (Exception e) {
Log.e("isInternetAvailable:",e.toString());
return false;
}
}
class IsInternetActive extends AsyncTask<Void, Void, String>
{
InputStream is = null;
String json = "Fail";
@Override
protected String doInBackground(Void... params) {
try {
URL strUrl = new URL("http://icons.iconarchive.com/icons/designbolts/handstitch-social/24/Android-icon.png");
//Here I have taken one android small icon from server, you can put your own icon on server and access your URL, otherwise icon may removed from another server.
URLConnection connection = strUrl.openConnection();
connection.setDoOutput(true);
is = connection.getInputStream();
json = "Success";
} catch (Exception e) {
e.printStackTrace();
json = "Fail";
}
return json;
}
@Override
protected void onPostExecute(String result) {
if (result != null)
{
if(result.equals("Fail"))
{
Toast.makeText(getApplicationContext(), "Internet Not Active", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Internet Active " + result, Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Internet Not Active", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPreExecute() {
Toast.makeText(getBaseContext(),"Validating Internet",Toast.LENGTH_LONG).show();
super.onPreExecute();
}
}
}
android studio How to continuously check if there is an active internet connection
You can use Runnable and post it using handler to continuously check internet connection every 5 second. Declare a global boolean variable isConnected and create a Runnable like:
private var isActiveNetwork= object : Runnable {
override fun run() {
try {
if(InetAddress.getByName("www.google.com").isReachable(5000))
{
isConnected = true
}
else{
isConnected = false
}
Handler().postDelayed(this,5000)
}
catch (e: Exception) {
isConnected = false
}
}
}
Now you can start this Runnable from network request callback:
override fun onAvailable(network: Network) {
super.onAvailable(network)
Handler().post(isActiveNetwork)
}
Android check internet connection
This method checks whether mobile is connected to internet and returns true if connected:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
in manifest,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
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;
}
}
Android Internet connectivity check better method
Try this:
It's really simple and fast:
public boolean isInternetAvailable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
sock.close();
return true;
} catch (IOException e) { return false; }
}
Then wherever you want to check just use this:
if (isInternetAvailable("8.8.8.8", 53, 1000)) {
// Internet available, do something
} else {
// Internet not available
}
How to check internet access on Android? InetAddress never times out
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?)
Extra: One-shot RxJava/RxAndroid
Example (Kotlin)
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 */}
Extra: One-shot RxJava/RxAndroid
Example (Java)
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 {
}
});
Extra: One-shot AsyncTask
Example
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 */ });
Detect if Android device has Internet connection
You are right. The code you've provided only checks if there is a network connection.
The best way to check if there is an active Internet connection is to try and connect
to a known server via http.
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
Of course you can substitute the http://www.google.com
URL for any other server you want to connect to, or a server you know has a good uptime.
As Tony Cho also pointed out in this comment below, make sure you don't run this code on the main thread, otherwise you'll get a NetworkOnMainThread exception (in Android 3.0 or later). Use an AsyncTask or Runnable instead.
If you want to use google.com you should look at Jeshurun's modification. In his answer he modified my code and made it a bit more efficient. If you connect to
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
and then check the responsecode for 204
return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
then you don't have to fetch the entire google home page first.
Android Check Internet connection continuously
I want to use it in every activity. How can I modify this code?
Create a BaseActivity
class which extends AppCompatActivity
, and then make all of your Activity
classes extend this BaseActivity class. Put your code to check internet connection in the BaseActivity
class. cheers :)
Detect whether there is an Internet connection available on Android
The getActiveNetworkInfo()
method of ConnectivityManager
returns a NetworkInfo
instance representing the first connected network interface it can find or null
if none of the interfaces are connected. Checking if this method returns null
should be enough to tell if an internet connection is available or not.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your android manifest.
Edit:
Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.
Related Topics
How Does Facebook Add Badge Numbers on App Icon in Android
Android - How to Take Screenshot Programmatically
What Is Difference Between Collection.Stream().Foreach() and Collection.Foreach()
How to Set the Style of List View Cells Based on a Condition in Javafx
Find First Element by Predicate
How to Implement "CSS Versioning" (To Solve Cache Issues) Using Jsf 2 H:Outputstylesheet
"Loadstylesheetunprivileged" Error When Trying to Use CSS Stylesheet with Javafx
Use of Initializers VS Constructors in Java
Is It Really Impossible to Protect Android Apps from Reverse Engineering
Mapstruct and Lombok Not Working Together
What Is the Basic Purpose of @Serializedname Annotation in Android Using Gson
Java Equivalent to PHP's Hmac-Sha1
Calculate Difference Between Two Times in Android
Resize Image to Full Width and Fixed Height with Picasso
Android App in Eclipse: Edit Text Not Showing on Graphical Layout