Detect network connection type on Android

前端 未结 14 1139
后悔当初
后悔当初 2020-11-22 05:55

How do you detect the network connection type on Android?

Is it through ConnectivityManager.getActiveNetworkInfo().getType(), and is the answer limited

14条回答
  •  有刺的猬
    2020-11-22 06:40

    On top of Emil's awsome answer I'd like to add one more method, for checking if you actually have Internet access as you could have data set to off on your phone.

    public static boolean hasInternetAccess(Context c){
        TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        if(isConnected(c) && tm.getDataState() == TelephonyManager.DATA_CONNECTED)
           return true;
        else
            return false;
    }
    

    Note that this is only for checking if theres a cellular data connection and will return false if you have WiFi connected, as the cellular data is off when WiFi is connected.

提交回复
热议问题