Connectivitymanager To Verify Internet Connection
Hi all I need to verify if my device is currently connected to internet or not and so I wrote this class that uses a ConnectivityManager to check: public boolean checkInternetConne
Solution 1:
package com.app.utility;
publicclassUtilities {
publicstaticfinalbooleanCheckInternetConnection(Context context) {
ConnectivityManagercm= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
returntrue;
} else {
returnfalse;
}
}
}
Solution 2:
The only issue with using getActiveNetworkInfo() is that there are a number of situations where is will not correctly detect connectivity. For example if the mobile network is disabled on a phone but wifi is available then the active network may still be counted as the mobile network and therefore return false.
An alternative is:
publicbooleanisOnline() {
ConnectivityManagercm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfonetInfoMob= cm.getNetworkInfo(cm.TYPE_MOBILE);
NetworkInfonetInfoWifi= cm.getNetworkInfo(cm.TYPE_WIFI);
if ((netInfoMob != null || netInfoWifi != null) && (netInfoMob.isConnectedOrConnecting() || netInfoWifi.isConnectedOrConnecting())) {
returntrue;
}
returnfalse;
}
Solution 3:
Thx Alan H!
The if condition may cause NPE when one of netInfoMob and netInfoWifi is null but the other not.
This one works for me:
netInfoMobile!=null&&netInfoMobile.isConnectedOrConnecting()||netInfoWifi!=null&&netInfoWifi.isConnectedOrConnecting()
Solution 4:
Try this , this code works.
publicstaticbooleancheckNetwork(Context context) {
context = context;
ConnectivityManagerconnManager= (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected())
|| (connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnected())) {
returntrue;
} else {
returnfalse;
}
}
Solution 5:
You can easily check with kotlin
.
funcheckInternetConnection(context Context) {
connectivityManager : ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if(connectivityManager.activeNetwork) {
returntrue
} else {
returnfalse
}
}
Post a Comment for "Connectivitymanager To Verify Internet Connection"