kotlin check if network connection code example
Example 1: Android check internet
/**
* @author Pratik Butani
*/
public class InternetConnection {
/**
* CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT
*/
public static boolean checkConnection(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr != null) {
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) { // connected to the internet
// connected to the mobile provider's data plan
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
}
return false;
}
}
Example 2: check if user has internet connection in kotlin
InternetCheck(object : InternetCheck.Consumer {
override fun accept(internet: Boolean?) {
Log.d("test", "asdasdas")
}
})