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" />