Created
July 31, 2021 04:57
-
-
Save AkaashSaini/03e8a0ec185cb63fe90a8ee02fa71d1d to your computer and use it in GitHub Desktop.
How to check Internet connection in android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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