Thursday, September 19, 2019

internet connection check in android studio

public class InternetConnectionDetector {

    private Context context;

    public InternetConnectionDetector(Context context) {
        this.context = context;
    }

    /**     * Checking for all possible Internet providers     * **/    public boolean isConnectedToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }

    /**     *     * @param context     * @param enabled     * @throws Exception     */
    public void connectToDataConnection(Context context, boolean enabled) throws Exception {
        final ConnectivityManager conman = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final Class conmanClass = Class.forName(conman.getClass().getName());
        final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
        connectivityManagerField.setAccessible(true);
        final Object connectivityManager = connectivityManagerField.get(conman);
        final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
        final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);

        try {
            setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**     *     * @param context     * @param ON     * @throws Exception     */
    public void connectToWifi(Context context, boolean ON) throws Exception
    {

        WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(ON);

    }
}

----------------------------------------------

/** * to checkInternet Connection in mobile devices */public void checkInternetConnection() {
    if (!internetDetector.isConnectedToInternet()) {
        showPopUp();
    }
}

--------------------
/** * show popup message to user. */public void showPopUp() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

    // Setting Dialog Title    alertDialog.setTitle("No Internet :(");

    // Setting Dialog Message    alertDialog.setMessage("Network connection is not available. Choose either of the options to get connected to a network.");

    // Setting Icon to Dialog    alertDialog.setIcon(R.drawable.nointernet);

    // Setting WiFi Yes Button    alertDialog.setPositiveButton("WiFi",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                                    int which) {

                    try {
                        internetDetector.connectToWifi(getApplicationContext(), true);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Toast.makeText(getApplicationContext(),
                            "Wifi Turned On",
                            Toast.LENGTH_SHORT).show();

                }
            });
    // Setting Data Connection Button    alertDialog.setNeutralButton("Mobile Data",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                                    int which) {

                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Settings.ACTION_DATA_ROAMING_SETTINGS);
                    startActivity(intent);
                }
            });
    // Setting Positive "Cancel" Button    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                                    int which) {
                    Toast.makeText(getApplicationContext(),
                            "Process Terminated!", Toast.LENGTH_SHORT)
                            .show();
                }
            });
    // Showing Alert Message    alertDialog.show();
}