find if there is an active internet connection java android - java

I'm trying to find out if there is an active internet connection in my app.
I need to know if I can access the network without any errors, sometimes I get "true" response even though I have not internet connection and that is because i'm still connected to the WiFi but there is no internet connectivity.
At the mean time, my internet check function is:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
This function only check if i'm connected to a certain WiFi or mobile network without actually checking if I can access the network.
So I've added the next function:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
return !ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
I don't know why, but this function always thinks that my internet connection is okay even though my router is not connected (I have this little yellow triangle on the network bar that says connected but no internet connection).
I tried printing everytime I call this function if the connection is true/false, and I get true at the time that i'm connected, I get false for 5-10 seconds right after I unplug my router, and then i'm getting true again... (without conencting to other WiFi network)
I've tried to test this on the ADB emulator and also on actual device, both of them crashed because I tried to access the network even though I was "offline".
Seeking for help!
Thank you very much.

instead of isConnected() method
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
try this
return activeNetwork !=null && activeNetwork.isConnectedOrConnecting();
this is the utility class I usually use:
public class NetworkHelper {
//method that checks for network status
public static boolean hasNetworkAccess(Context context){
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork !=null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Make sure you have permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
in your activity make a
private boolean networkOk;
then use it to see if your connection is ok
ex
networkOk = NetworkHelper.hasNetworkAccess(this);
if (networkOk) {
Intent intent = new Intent(MainActivity.this, Myservice.class);
intent.setData(Uri.parse(jsonurl));
startService(intent);
}

This is what worked for me:
public boolean hasNetworkAccess() {
if (hasActiveInternetConnection()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.screens.company").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
System.out.println("NETWORK CHECK");
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e("NETWORK", "Error checking internet connection.");
}
} else {
Log.d("NETWORK", "No network available!");
}
return false;
}
public boolean hasActiveInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
System.out.println("Debug: [Network] Status: " + (activeNetwork != null && activeNetwork.isConnectedOrConnecting()));
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
System.out.println("Debug: [Network] Status: NOT CONNECTED.");
e.printStackTrace();
return false;
}
}

this will actually check for internet
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetStatus {
private static NetStatus instance = new NetStatus();
static Context context;
ConnectivityManager connectivityManager;
boolean connected = false;
public static NetStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
boolean online = false;
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
if (connected) {
if (isInternetWorking()) online = true;
}
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return online;
}
public boolean isInternetWorking() {
boolean success = false;
try {
URL url = new URL("http://www.google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Android");
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(1000);
connection.setReadTimeout(1000);
connection.connect();
if (connection.getResponseCode() == 200) success = true;
connection.disconnect();
} catch (IOException e) {
//e.printStackTrace();
}
return success;
}
}

Related

Check is Internet available - Should we check for NetworkCapabilities.TRANSPORT_BLUETOOTH, TRANSPORT_VPN, ... as well?

Previously, before API 28, we can use NetworkInfo, to check whether Internet is available without much effort. A single call on isConnectedOrConnecting will be sufficient enough.
private static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
// Will it happen ever?
return false;
}
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
But, quite a number of methods of NetworkInfo is deprecated. Hence, we need to modify our code to
private static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
// Will it happen ever?
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Network activeNetwork = cm.getActiveNetwork();
if (activeNetwork == null) {
return false;
}
NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(activeNetwork);
if (networkCapabilities != null) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
return true;
}
}
return false;
} else {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
We was wondering, should we perform check on the following remaining capabilities, to determine whether Internet is available?
TRANSPORT_BLUETOOTH
TRANSPORT_VPN
TRANSPORT_WIFI_AWARE
TRANSPORT_LOWPAN
As, it is difficult to have access to all kinds of network connection, and we do not have luxury to do all the cases testing.

How can I check internet connection in Android Q?

Before Android Q all you had to do is use the NetworkUtils class. But this class was deprecated in API 29.
I've been searching for an alternative, and I couldn't seem to find one.
So, how can I check the 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;
}
Add the below permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
If you are looking for a simple code, you can use this:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return cm.getActiveNetwork() != null && cm.getNetworkCapabilities(cm.getActiveNetwork()) != null;
} else {
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
The ConnectivityManager only checks whether the smartphone could theoretically establish an Internet connection. Whether an Internet connection actually exists, e.g. if the network quality is very poor, can only be determined with a ping or a web address.
Just use this code and call isInternatAvailable(context).
private static final String CMD_PING_GOOGLE = "ping -w -c 1 google.com";
public static boolean isInternetAvailable(#NonNull Context context) {
return isConnected(context) && checkInternetPingGoogle();
}
public static boolean isConnected(#NonNull Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} else {
return false;
}
}
public static boolean checkInternetPingGoogle(){
try {
int a = Runtime.getRuntime().exec(CMD_PING_GOOGLE).waitFor();
return a == 0x0;
} catch (IOException ioE){
EMaxLogger.onException(TAG, ioE);
} catch (InterruptedException iE){
EMaxLogger.onException(TAG, iE);
}
return false;
}

Import deprecated warning after updating target sdk to 29

After updating compile and targetSdkVersion to "29" in build.gradle I get deprecation warning:
warning: [deprecation] NetworkInfo in android.net has been deprecated
import android.net.NetworkInfo;
^
Build fails because of this. But I use Network info to have compatibility with api versions 16-29. How should I handle deprecated imports targeting api "29" and above?
I found the solution to this one. You must write the method in this way.
#SuppressWarnings("deprecation")
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) AnkiDroidApp.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
/* NetworkInfo is deprecated in API 29 so we have to check separately for higher API Levels */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Network network = cm.getActiveNetwork();
if (network == null) {
return false;
}
NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
if (networkCapabilities == null) {
return false;
}
boolean isInternetSuspended = !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED);
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
&& !isInternetSuspended;
} else {
android.net.NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
Remember to suppress warning.
The Answer of your question is in this Link!
NetworkCapabilities is not deprecated in API 29 but it requires API 21 so I have called it on API 29 only.
public static boolean isNetworkAvailable(Context context) {
if(context == null) return false;
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if
(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
return true;
}
}
}
else {
try {
NetworkInfo activeNetworkInfo =
connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Log.i("update_statut", "Network is available : true");
return true;
}
} catch (Exception e) {
Log.i("update_statut", "" + e.getMessage());
}
}
}
Log.i("update_statut","Network is available : FALSE ");
return false;
}

How to put this piece of code into an AsyncTask or a Thread

Im new in threads and AsyncTask's and I would like to know how can I run the following code in the background:
I have this method which checks if you have an active internet conection, what Im trying to do is to show a ProgressDialog before calling the method and dismissing the dialog when succeed or fail:
Oncreate:
progress = ProgressDialog.show(this, "dialog title","dialog message", true);
if(isOnline()){}else{}
My method.
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.karlol.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
canshowview = true;
progress.dismiss();
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
The method works well (It tells me if there's an active internet connection) the problem is that the AlertDialog is not working as I would like to, so Im pretty sure if I put this into a Thread or AsynTask it should work as I want.
UPDATE:
I use ConnectivityManager to check if the user us connected to a network, but this does not verify the connection
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Thanks.
I dont think that this is the best way to get the result you are looking for but here it is
(AsyncTask<String,String,Boolean>(){
protected Boolean doInBackground(String... params) {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.karlol.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
canshowview = true;
progress.dismiss();
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false
}
protected void onPostExecute(Boolean result)
{
/// do something here
super.onPostExecute(result);
}
}).execute()
I would look at using as a better solution to your problem
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}

Check internet status from the main activity

I'm new student on android development, so I don't have the enough experience for coding, so I need the help from you...
I create a java class on android studio to check if there is an internet connection or not :
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class InternetStatus {
private static final String LOG_TAG ="InternetStatus";
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable((Activity) 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;
}
public static boolean isNetworkAvailable(Activity mActivity) {
Context context = mActivity.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
}
So, I have two questions :
1- is this the right code or I'm missing something ?
2- as you see this is a java class, if I create a button on my main activity to check if there is an internet connection or not !! how I can do that by importing this class or something like that ?!!
// Check if there is any connectivity for a Wifi network
public boolean isConnectedWifi(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
}
// Check if there is any connectivity for a mobile network
public boolean isConnectedMobile(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE;
}
// Check all connectivities whether available or not
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
How to use?
For example, we need to check if the connectivity is available:
if(isNetworkAvailable()){
// do your thing here.
}
When the network is available, we need to check whether it is WiFi or Mobile network:
if(isConnectedWifi()){
// do your thing here with WiFi Network.
}
if(isConnectedMobile()){
// do your thing here with Mobile Network.
}
First of all, you must include a permission request in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then, create a method to check if internet connection is active:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
In your MainActivity class
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
boolean isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
}
}
if you have a button
boolean isavailable ;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
Button someButton = (Button) findViewById(R.id.yourButton);
someButton.setOnClickListener(new onClickLIstener(){
isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
});
}
}
To check the connectivity status no need to connect to internet and get status code. Use below code.
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
Which will return true or false based on active network status.
On your button click simply call this function, If it returns true, there is a connection. If it returns false, there is no active internet connection.
Just Put info.isConnected() in your isNetworkAvailable function:
public static boolean isNetworkAvailable(Activity mActivity) {
...
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null && info.isConnected()) {
...
}
}
}
return false;
}
Most of the answers are outdated
fun isNetworkAvailable(context : Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (isAndroidVersionAboveLollipop()) {
val activeNetwork = connectivityManager.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
networkCapabilities.let {
return it.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && it.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
} else {
return connectivityManager.activeNetworkInfo?.isConnectedOrConnecting ?: false
}
}
fun isAndroidVersionAboveLollipop() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M

Categories

Resources