问题描述
我的应用程序需要一种功能来检查用户的手机是否已打开手机数据。
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(),1) == 1;
}
}
此代码可在我的大多数手机中使用。
“诺基亚8”(Android 9)除外
为什么?
解决方法
您是否真的需要检查是否启用或禁用了移动数据设置,或者您真正想做的是检查设备当前是否具有移动数据连接?
如果是后一种情况,则应使用CONNECTIVITY_SERVICE
,例如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);
上面的docs链接还包含一些您可能要检出的其他相关类的链接,例如NetworkInfo.DetailedState
和ConnectivityManager.NetworkCallback
对此进行检查,是否有帮助:
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
}
}
}