Question

I'm trying to check internet connection in activity. And i'm using alerts to turn on Wi-Fi when there is no internet connection.

And I don't know what to do. My program makes 5 or more alerts. What can I do to change it?

Was it helpful?

Solution

To check the Internet Connection the following method will be helpful. Alert Dialog will be called from in the if loop when there is no internet connection to activate the Wifi Connection.

public static void checkTheNetworkAvailability(Context con) {
        Context mycontext = con;
        ConnectivityManager myconnectivity = (ConnectivityManager) mycontext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (myconnectivity == null) {
            return false;
            // failed null!..
                    //show the alert box here for WiFi enabling
                    alert.show();
        } else {
            NetworkInfo[] myinfo = myconnectivity.getAllNetworkInfo();
            if (myinfo != null) {
                for (int i = 0; i < myinfo.length; i++) {
                    if (myinfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

The Alert Dialog will be as follows

wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Message")
        .setTitle("Title")
        .setCancelable(true);
        builder.setPositiveButton("Wifi On", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {


                        wifiManager.setWifiEnabled(true);

                    }
                });
        builder.setNegativeButton("Wifi Off", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                wifiManager.setWifiEnabled(false);
            }
        });

        AlertDialog alert = builder.create();

And add the below permissions in Manifest file

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

OTHER TIPS

Reuse the same AlertDialog instead of creating a new one each time the app has connection problems. You can use the isShowing() method for checking if the AlertDialog is being shown, so you don't need to show it again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top