I am trying to programmatically detect, when an Android phone is triggering this "warning", that the established internet connection currently seems to be unreachable (In this case: Edge / 2G), like this:
Indeed when this warning appears, the internet cannot be accessed, without it, it works.
What i am currently doing is to detect the correct network:
public String getNetworkClass() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
return "Unknown";
} else {
int networkType = mTelephonyManager.getNetworkType();
Log.i("NETWORK", String.valueOf(networkType));
mobileNetworkType = networkType;
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return "2G";
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE:
return "4G";
case TelephonyManager.NETWORK_TYPE_NR:
return "5G";
default:
return "Unknown";
}
}
}
When it is 2G, i am measuring the download / upload rate. I orientated myself here to guess that a download rate below 150 kbps might cause that "warning":
if(Arrays.asList(new String[]{"2G"}).contains(getNetworkClass())) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
int downSpeed = nc.getLinkDownstreamBandwidthKbps();
int upSpeed = nc.getLinkUpstreamBandwidthKbps();
if(downSpeed < 150) {
// I assume the connection is bad here
} else {
// All fine!
}
However, my measured values are between 30 and 100 kbps (every five seconds), and sometimes within this range, the warning appears, sometimes not.
How can i successfully capture this? Is there any Android interface to check this? If possible, i would like to avoid ping checks like:
public boolean canAccessInternet() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
System.out.println("Network mExitValue " + exitValue);
return (exitValue == 0);
} catch (IOException e) {
System.out.println(" IO Error ");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println(" Interrupted Error ");
e.printStackTrace();
}
return false;
}