How to Check Internet Connection in Android Programmatically, prevent your app from crashing if the user isn’t connected to the internet.
Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!
Developing some Android app that uses Retrofit, Volley or OkHTTP3 kind of libraries that fetch data from the internet is quite common in apps today.
However not having a user prompt to connect to the internet when its not available can actually crash your app and make your Android App user experience terrible.
In this blog learn how to show an alert to your user if he is not connected to the internet.
How to Check Internet Connection in Android Programmatically
Getting Started
Create an empty activity in your new Android Studio project. Now when the app is open we want in the main activity to show a prompt to the user about ‘No Internet Connection’. To achieve this create and call this function in your app’s onCreate() method.
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
In the code above, it’s a haveNetworkConnection() Java method that returns a boolean (true or false).
Using ConnectivityManager class the availability of WiFi or Mobile network is checked and if either of them isn’t available then the method returns false which should then prompt a dialog box and method for a dialog box is as follows:
private void showDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connect to wifi or quit")
.setCancelable(false)
.setPositiveButton("Connect to WIFI", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
this.finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
You can call both these methods in MainActivity.java’s onCreate() method like this:
if(haveNetworkConnection() == true){
//Call your async task here!
}
else{
showDialog()
}
Voila! now run your App without Intenet connection and post your experience below!