En android. Compruebe si los datos móviles están activados o desactivados

Aug 19 2020

Mi aplicación necesita una función para verificar que el teléfono móvil del usuario haya activado los datos móviles o no.

He hecho referencia a este enlace: # 32239785

Aquí está el código proporcionado en ese tema

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;
    }
}

Este código funciona en la mayoría de mis teléfonos móviles.

Excepto en "Nokia 8" (Android 9)

Incluso apagué los datos móviles. Esta función todavía devuelve verdadero.

¿Por qué?

Respuestas

marmor Aug 20 2020 at 11:36

¿Realmente necesita verificar si la configuración de datos móviles está habilitada o deshabilitada, o lo que realmente está tratando de hacer es verificar si el dispositivo tiene actualmente una conexión de datos móviles?

Si es el último caso, debería usar CONNECTIVITY_SERVICE, ejemplo de los documentos :

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);

El enlace de documentos anterior también tiene algunos enlaces a otras clases relevantes que quizás desee consultar como NetworkInfo.DetailedStateyConnectivityManager.NetworkCallback

DiwakarSingh Aug 20 2020 at 11:40

Consulte con esto, si ayuda:

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
    }
}
}