Check internet connection in android (not network connection)

旧街凉风 提交于 2019-11-29 16:03:03

I'm using broadcast to check the connection every time. Create a class for connection info.

import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class ConnectivityStatus extends ContextWrapper{

    public ConnectivityStatus(Context base) {
        super(base);
    }

    public static boolean isConnected(Context context){

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo connection = manager.getActiveNetworkInfo();
        if (connection != null && connection.isConnectedOrConnecting()){
            return true;
        }
        return false;
    }
}

Apply code into your Activity:

 private BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            // no connection
        }else {
            // connected
        }
    }
 };

Register broadcast in your activity's onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ..
    ...
    ....
  }

Don't forget to unregistered/register on Activity cycle:

@Override
protected void onResume() {
    super.onResume();
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

}

@Override
protected void onPause() {
    super.onPause();
    your_activity_context.unregisterReceiver(receiver);

}
saiRam89

You can use below code to check whether network connection is available or not.

public class NetworkConnection {
    public Context context;

    public NetworkConnection(Context applicationContext) {
        this.context=applicationContext;
    }

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

public class MainActivity extends AppCompatActivity {
    NetworkConnection nt_check;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        nt_check=new NetworkConnection(context);
        if(nt_check.isOnline()) {
            // do logic
        } else {
            // show message network is not available.
        }
    }
}
Ashish Gupta

Just check this LINK Here is the answer for both Connection & Internet.

You can do it like this

uses-permission android:name="android.permission.INTERNET"

uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

 private boolean checkInternet(Context context) {
    // get Connectivity Manager object to check connection
    ConnectivityManager connec
            =(ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);

    // Check for network connections
    if ( connec.getNetworkInfo(0).getState() ==
            android.net.NetworkInfo.State.CONNECTED ||
            connec.getNetworkInfo(0).getState() ==
                    android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() ==
                    android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
        Toast.makeText(context, " Connected ", Toast.LENGTH_LONG).show();
        return true;
    }else if (
            connec.getNetworkInfo(0).getState() ==
                    android.net.NetworkInfo.State.DISCONNECTED ||
                    connec.getNetworkInfo(1).getState() ==
                            android.net.NetworkInfo.State.DISCONNECTED  ) {
        Toast.makeText(context, " Not Connected ", Toast.LENGTH_LONG).show();
        return false;
    }
    return false;
}
public static boolean isNetworkAvailable(Context context) {
    try {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService
                (Context.CONNECTIVITY_SERVICE);
        if (connManager.getActiveNetworkInfo() != null && connManager.getActiveNetworkInfo()
                .isAvailable() && connManager.getActiveNetworkInfo().isConnected()) {
            return true;
        }
    } catch (Exception ex) {

        ex.printStackTrace();
        return false;
    }
    return false;
}

then just call this function from your fragment or Activity will work

To check if internet connection is available or not, you can use the below code snippet

    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", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

This code snippet will also help you to identify whether you device is having internet connection even if you are connected through wifi network.

Note: make sure to call this method in background thread ,because this can take time depending on your network speed, and should not be called in Main thread

This is what i try in android to check internet connection it is not sleek solution but does the work given you have already checked for the network :

try {
      HttpURLConnection urlConnection = (HttpURLConnection)
      (new URL("http://clients3.google.com/generate_204")
      .openConnection());
      urlConnection.setRequestProperty("User-Agent", "Android");
      urlConnection.setRequestProperty("Connection", "close");
      urlConnection.setConnectTimeout(1500);
      urlConnection.connect();
      if (urlConnection.getResponseCode() == 204 &&
      urlConnection.getContentLength() == 0) {
      Log.d("Network Checker", "Successfully connected to internet");
      return true;
      }
      } catch (IOException e) {
      Log.e("Network Checker", "Error checking internet connection", e);
      }

It's accurate for me.Try and let me know if you find any other good solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!