Skip to content

Instantly share code, notes, and snippets.

@AkaashSaini
Created July 31, 2021 04:57
Show Gist options
  • Save AkaashSaini/03e8a0ec185cb63fe90a8ee02fa71d1d to your computer and use it in GitHub Desktop.
Save AkaashSaini/03e8a0ec185cb63fe90a8ee02fa71d1d to your computer and use it in GitHub Desktop.
How to check Internet connection in android
// add permission to menifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
//create method to check connection
//check mobile network
private boolean isNetworkConnected(){
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
Log.i("clash", "isNetworkConnected: "+isConnected);
return isConnected;
}
//check other network
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
//if else to check connection in oncreate
if (isNetworkConnected() || isInternetAvailable()){
//internet is connected!
}
else{
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("No Internet!")
.setMessage("Please Turn On Your Internet!")
.setNegativeButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
recreate();
}
}).show();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment