Detect network connection type on Android

前端 未结 14 1453
后悔当初
后悔当初 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:48

    @Emil's answer above is brilliant.

    Small addition: We should ideally use TelephonyManager to detect network types. So the above should instead read:

    /**
     * Check if there is fast connectivity
     * @param context
     * @return
     */
    public static boolean isConnectedFast(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(), tm.getNetworkType()));
    }
    

提交回复
热议问题