In my application I am checking whether the mobile is connected to the internet or not, using WIFI or mobile data connection but the problem is my code is always showing internet connection not available through my device is connected to WIFI.
Here is the code where I am inspecting the internet connection.
public class InternetDetector {
private Context mcontext;
public InternetDetector(Context context) {
this.mcontext = context;
}
public boolean checkMobileInternetConn() {
ConnectivityManager connectivity = (ConnectivityManager) mcontext
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (info != null) {
if (info.isConnected()) {
return true;
}
}
}
else if (connectivity != null) {
NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (info != null) {
if (info.isConnected()) {
return true;
}
}
}
return false;
}
}
and this is how I am using this class in other activities to check the connection.But the code is always going to the else part and always shows the toast.
if (allValid) {
isConnectionExist = internetDetector.checkMobileInternetConn();
if (isConnectionExist) {
try {
new MyAsyncClass().execute();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
Permissions which I have given under Manifest file are:-
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>