Issue
I'm using the following piece of code to check if a phone is connected to internet (either WiFi or mobile data):
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
}
} else {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return (activeNetworkInfo != null) && activeNetworkInfo.isConnected();
}
It could be the case that a phone is connected to WiFi but not to internet. For my use case I assume that when it is connected to WiFi or mobile network (with mobile data enabled) that internet will be available.
Is this piece of code ok? Especially, does activeNetworkInfo.isConnected() also test for mobile data or only WiFi? I'm targeting Android 7 to Android 10. Theoretically I could use the the piece of code in the if-clause also for devices below Android 10 I think.
Solution
First ask for this permission to the manifest.xml : android.permission.ACCESS_NETWORK_STATE
In android, we can determine the internet connection status easily by using WIFIMANAGER.
private boolean LookForWifiOnAndConnected() {
WifiManager wifi_m = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
if (wifi_m.isWifiEnabled()) { // if user opened wifi
WifiInfo wifi_i = wifi_m.getConnectionInfo();
if( wifi_i.getNetworkId() == -1 ){
return false; // Not connected to any wifi device
}
return true; // Connected to some wifi device
}
else {
return false; // user turned off wifi
}
}
// check if mobile data on or off
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
Answered By - Rashad Nasirli
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.