Android tutorial

Android Detect Internet Connection Status

Android Detect Internet Connection Status

Android Detect internet connection status in your app. This is very easy. In this article, you will learn how to detect internet connection in android app status manually and automatically. Using a broadcast receiver, your app will be automatically notified when there is a change in the network connection.

Creating New Project:-

Step 1 : First one to  Start Android Studio

Step 2 :  Seconds step to Create a New Project Project Click On  ==> File  ==> NEW ==> New Project.When it prompts you to select the default activity, select Empty  Activity and proceed.

Step 3:  Create a class name AppStatus.java and extend it from BroadcastReceiver. This is a receiver class that will be notified whenever there is a change in network/internet connection. Open your java file and copy-paste the code

public class AppStatus {
    private static AppStatus instance = new AppStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;

    }
}

Android internet connection check

Step 5:  Create another Activity name MainActivity.java and extend it from Application. This class will be called whenever the app is launched. Here AppStatus.getInstance.

Step 6:  Add this code in onCreate where you check the Internet connection.

if (AppStatus.getInstance(this).isOnline()) {
} else {
    ContextThemeWrapper ctw = new ContextThemeWrapper( Home.this, R.style.Theme_AlertDialog);
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
    alertDialogBuilder.setTitle("NO Internet Connection");
    alertDialogBuilder.setMessage("Check your  Internet Connection or Try again");
    alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {

        }
    });
    alertDialogBuilder.show();
}

Step 7: Open AndroidManifest.xml and do the below changes. And add permission.

<uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />