How can I get connection is available or not on Android?
I tried lots of code, but I did not get the correct result.
How can I get connection is available or not on Android?
I tried lots of code, but I did not get the correct result.
Put in this function and call it at the starting of your Activity:
void checkInternetConnectionStatus()
{
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
/*
* Toast.makeText(this, "Wi-Fi connection enabled",
* Toast.LENGTH_LONG) .show();
*/
} else if (mobile.isAvailable()) {
/*
* Toast.makeText(this, "Mobile Internet enabled",
* Toast.LENGTH_LONG) .show();
*/
} else {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG)
.show();
new AlertDialog.Builder(this)
.setTitle("No internet connection active")
.setMessage("Please start internet connection and run this application.")
.setNegativeButton(
"Exit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Negative");
finish();
}
}).show();
}
}
Maybe this will help:
ConnectivityManager conn = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifi.isConnected()) {
// Do your code
}
And also you need to add in AndroidManifest.xml:
android.permission.ACCESS_NETWORK_STATE
And also this link will help: