问题
My app need a function to check user's mobile phone has turned on the mobile data or not.
I have referenced this link: #32239785
Here is the code provided in that topic
boolean mobileYN = false;
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
{
mobileYN = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
}
else{
mobileYN = Settings.Secure.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
}
}
This code works in most of my mobile phone.
Except on "Nokia 8"(Android 9)
Even I turned off the mobile data. This function still return true.
Why?
回答1:
Do you really need to check whether the setting for mobile-data is enabled or disabled, or what you really trying to do is check if the device currently has mobile-data connection?
If it's the latter case, you should be using CONNECTIVITY_SERVICE
, example from the docs:
private static final String DEBUG_TAG = "NetworkStatusExample";
...
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isWifiConn = false;
boolean isMobileConn = false;
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
isWifiConn |= networkInfo.isConnected();
}
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
isMobileConn |= networkInfo.isConnected();
}
}
Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);
The above docs link also has some links to other relevant classes you might want to check out like NetworkInfo.DetailedState and ConnectivityManager.NetworkCallback
回答2:
Check with this, if it helps:
class InternetNetwork {
companion object {
fun isOnline(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null)
when {
capabilities.hasTransport(TRANSPORT_CELLULAR) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
return true
}
capabilities.hasTransport(TRANSPORT_WIFI) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
return true
}
capabilities.hasTransport(TRANSPORT_ETHERNET) -> {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
return true
}
}
} else {
val connectivityManage =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = connectivityManage.activeNetworkInfo
return netInfo != null && netInfo.isConnected
}
return false
}
}
}
来源:https://stackoverflow.com/questions/63486187/in-android-check-whether-mobile-data-is-on-or-off