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;
}
}
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 */ });
How to check currently internet connection is available or not in android
This will tell if you're connected to a network:
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
connected = false;
Warning: If you are connected to a WiFi network that doesn't include internet access or requires browser-based authentication, connected
will still be true.
You will need this permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
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();
}
}
}
How can I check internet connection in Android Q?
Use this code snippet.
@IntRange(from = 0, to = 3)
public static int getConnectionType(Context context) {
int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = 2;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = 1;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
result = 3;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = 2;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = 1;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_VPN) {
result = 3;
}
}
}
}
return result;
}
Happy Coding :)
Check internet connectivity android in kotlin
Call the AsyncTask this way, it should work. You don't need to change anything in your InternetCheck AsyncTask. Basically you need to pass in an object that implements the Consumer interface that's defined in the InternetCheck class.
InternetCheck(object : InternetCheck.Consumer {
override fun accept(internet: Boolean?) {
Log.d("test", "asdasdas")
}
})
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
Android Activity Life Cycle - What Are All These Methods For
How to Add Parameters to Httpurlconnection Using Post Using Namevaluepair
How to Refresh Android Listview
How to Implement Endless List With Recyclerview
How to Disable Orientation Change on Android
Ioexception: Read Failed, Socket Might Closed - Bluetooth on Android 4.3
Integrating the Zxing Library Directly into My Android Application
Difference Between a View'S Padding and Margin
How to Get a List of Installed Android Applications and Pick One to Run
Sending and Parsing Json Objects in Android
Get Real Path from Uri, Android Kitkat New Storage Access Framework
What Is the Main Purpose of Settag() Gettag() Methods of View
Java Finished With Non-Zero Exit Value 2 - Android Gradle
How to Use Recyclerview Inside Nestedscrollview