0

I want to check whether ''Wifi' is connected, but how to detect internet is available or not? Because within my 'MainActivity.java' I' checking the internet connection and also the availability of internet by following code.

public static boolean isConnectedToInternet(Context context) {

   ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        Log.d("INTERNET_CONNECTION", "Internet is working");

        return true;
    } else {
        Log.d("INTERNET_CONNECTION", "Internet is Not Available");
        return false;
    }

}

If internet is available (data and signal is ok), visible the 'Progress bar' and load the content and loading process is completed invisible the 'Progress bar'. If internet is not available (no data or no signal), invisible the 'Progress bar' and display an error.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        if (isConnectedToInternet(context)== true)
        {
            progressLayout.setVisibility(View.VISIBLE);

            // load the content
        }
        else
        {
            progressLayout.setVisibility(View.GONE);

            Toast.makeText(this, "No Internet", Toast.LENGTH_LONG).show;
        }
}

If internet is available code is working properly, but 'Progress bar' is always displaying when internet is not available. (no data or no signal)

James Z
  • 12,209
  • 10
  • 24
  • 44
Nuwan Withanage
  • 393
  • 7
  • 19

1 Answers1

0
 public static boolean isNetworkAvailable(Context activity) {
    ConnectivityManager connectivity = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (NetworkInfo anInfo : info) {
                if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}
Gautam Surani
  • 1,136
  • 10
  • 21