0

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 ?!!

Amir
  • 37
  • 14
mohamd jado
  • 23
  • 1
  • 1
  • 8

6 Answers6

8
// 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.
}
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87
  • 2
    thanks bro :) this is the best answer (Y),, and it works 100%, but something is missing here which is "Connectivity" class, you have to build it, and i google it and see the class here : (http://stackoverflow.com/questions/2802472/detect-network-connection-type-on-android) – mohamd jado Jan 27 '15 at 14:23
  • 1
    i want to vote up for your answer but i don't have enough reputation :( – mohamd jado Jan 27 '15 at 14:26
  • Thanks back for your info about the missing. Take +1 from me. – Anggrayudi H Jan 28 '15 at 07:34
1

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();
}
Silvio Delgado
  • 6,798
  • 3
  • 18
  • 22
0

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);
     });
    }
}
Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
0

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.

Vilas
  • 1,695
  • 1
  • 13
  • 13
0

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;
        }
arpit
  • 1,462
  • 1
  • 12
  • 12
0

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
San
  • 5,567
  • 2
  • 26
  • 28