I just want to implement a query that checks which WiFi/Mobile settings are enabled every time I click the button. I get weird results with my code.
How can I implement the correct behavior so that I know which adapters are turned on and which are not?
private fun check() {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.run {
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)?.run {
if (hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
Log.d("TAG", "WIFI YES")
} else {
Log.d("TAG", "WIFI NO")
}
if (hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
Log.d("TAG", "MOBILE YES")
} else {
Log.d("TAG", "MOBILE NO")
}
}
}
}
WiFi Mobile --output--> WiFi Mobile
× × no output
✓ × yes no
× ✓ no no
✓ ✓ yes no
Try the below line of code to check connection according to your requirement you can use it
public static boolean isNetworkConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager)TaxiappApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo bluetooth = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_BLUETOOTH);
NetworkInfo wimax = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIMAX);
if (wifi == null && mobile == null && bluetooth == null && wimax == null) {
return false;
}
if (wifi != null && wifi.isConnected()) {
return true;
}
if (mobile != null && mobile.isConnected()) {
return true;
}
if (bluetooth != null && bluetooth.isConnected()) {
return true;
}
if (wimax != null && wimax.isConnected()) {
return true;
}
return false;
}
hope it will help for you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.