Skip to main content

How to Check Internet Connection in Android Programmatically

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 yourAndroid App user experience terrible. 

How to Check Internet Connection in Android Programmatically


However, to prevent this from happening with your app, How to Check Internet Connection in Android Programmatically ?

Well, here are few lines of code for your Android Project:

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;
}

It's a haveNetworkConnection() Java method that returns a boolean (true or false). Using ConnectivityManager classthe availability of WiFi or Mobile network is checked and if either of them isn't available then 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 and have a

if(haveNetworkConnection() == true){
    //Call your Retrofit or okHTTP3 library!
}

else{
   showDialog()
}

TaDa! now run your App without Intenet connect and post your experience below!

You can also check a similar app built by our team here for Website Bloggers and Developers here:

Search Console | Android App

Comments

Popular posts from this blog

How To Open PDF File in Android Application Example Included

Want to know How To Open PDF File in Android Application Example. To open a PDF File in Android Application, your app can take help from Free Android library available on Github.

Here are few apps made from PDF Library you can look at, click here to know more.

By using Android Library you are not only leveraging the hard work from another developer but also making it easier and quicker to develop an android app.
How To Open PDF File in Android Application Example  In this tutorial series, we will teach you how to open a pdf file in Android Application Example included with the help of Android PDFViewer library developed by Barteksc.

Get inspirtion from here: Top 7 PDF Download for Mobile Android Apps

Before I proceed further, here is the screenshot of the kind of PDF Viewer that’ll be created using Android Studio.



 How To Open PDF File in Android Application Example

The app will open a specified pdf file which will be copied in the assets folder of your Android studio project. I'v…

Open Weather Map API Example | Create Android Weather App

In this tutorial blog, using open weather map API example, we will create an Android weather app. The Android App will able to access Open weather map website server and access weather details of particular location.

The App will look similar to the image shown below. It will fetch real time weather of the location provided in MainActivity.Java file.


Software / Files used:Android Studio (Version 3.x) Files Edited / Created:activity_main.xmlMainActivity.JavaWeather.JavaAndroidManifest.xml Steps Involved in Open Weather Map API Example: Here are the Steps you need to follow on ‘Open Weather map API Example’ to create Android Weather App:

1. Open the Open Weather map API link provided here. Sign up for Current Weather Data API key here.

2. Once the key is received, save it to notepad or on stick notes.

3. Open Android Studio and create a new Project with name, ‘FIMC Weather App’, we will select an empty activity in the wizard and wait for Gradle build.



4. Open AndroidManifest.xml…

Android Live Wallpaper Tutorial (using Android Studio 3.x) | FaultInMyCode

The Android Live Wallpapers are the way to redesign your mobile background into something amazing animated GIF using different effects and motions. Many novice developers are making good money by Henceforth here is Android Live Wallpaper tutorial for you to build your own Live wallpaper and start earning today as a developer!



This tutorial is a part of our Blog series on ‘Roadway to Android Development Course’, its suitable for Beginners to programming as well as the android enthusiast to learn about Android development and build their own apps.

In this tutorial for beginners, you’ll learn how by using Android Studio 3.0 and by having basic knowledge of Java, we will teach you to build your own Live wallpaper for Android which you may later publish in the Google Play Store. We assume you have some experience with Android studio, if not please check how to build your own calculator app and how to create simple login app in Android Studio 3.x tutorial.
How to build Android …