Mashuk Khan
Mashuk Khan

Reputation: 67

Internet connection issue

In my app I am checking internet connection with below method :

public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

Now, in activity I am checking for internet connection as below :

if (Constant.isOnline(mContext))
   loadNotificationList();
else
   Constant.displayToast(mContext, getResources().getString(R.string.msg_internet));

Now, If MobileData or wi-fi is off I am getting toast message. It's fine. But, the issue is in below scenario :

==> I am using wi-fi of another device in which hotspot is on and my device got connected to it. now, I have turned off the mobile data of that another device. that means: no internet access for me. But, still i am getting true from the method : isOnline()

so, I think the method is checking for the state only. What if I wanna go check that internet access is available in real or not?

Thanks.

Upvotes: 0

Views: 225

Answers (3)

sHOLE
sHOLE

Reputation: 343

I had used the below approach for my project. I made a class CheckInternet. The idea is to check if you're connected to any network using isNetworkAvailable() If so, then checking for internet connectivity by pinging a server and checking for response (preferable Google) in hasActiveInternetConnection()

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 CheckInternet {

    private static final String TAG = CheckInternet.class.getSimpleName();
    protected Context context;

    public CheckInternet(Context context) {
        this.context = context;
    }

    private static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public static boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();

                return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.e(TAG, "Error checking Internet Connection - " + e);
            }
        } else {
            Log.d(TAG, "No network available!");
        }
        return false;
    }
}

You call this class anywhere via a Thread (since calling it directly would throw a NetworkOnMainThreadException ). Below is how I called it in a Fragment.

Thread th = new Thread(new Runnable() {
    public void run() {
        Boolean b = CheckInternet.hasActiveInternetConnection(getContext());

        if (b) {
            //Net is working, do whatever
        } else {
            //Net is NOT working
        }
    }
});
th.start();

Upvotes: 1

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75798

If MobileData or wi-fi is off I am getting toast message

 if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }

Problem

  • Your return type

You should try this way,

 public static boolean isOnline(Context context) 
        {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo == null)
                return false;
            if (!netInfo.isConnected())
                return false;
            if (!netInfo.isAvailable())
                return false;
        return true;
       }

Upvotes: 0

Vidhi Thummar
Vidhi Thummar

Reputation: 33

Below method for Network is available or not.

    public static boolean isNetworkAvailable(Context mContext) {

    ConnectivityManager cm = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        Log.e("Network Testing", "***Available***");
        return true;
    }
    Log.e("Network Testing", "***Not Available***");
    return false;
}

in activity checking for internet connection.

  if(Utils.isNetworkAvailable(mContext)){

        isInternetAvailable = true;

    }else{
        isInternetAvailable = false;
    }

Upvotes: 0

Related Questions