Android 判断当前网络连接类型

实际应用开发时,如果存在需要用户获取大量数据的情况,最好是先判断下网络类型,提示用户当前的网络类型,是否需要连接Wifi,etc.
(手机流量太贵啦,当然土豪是无视这玩意的, (/ □ \)).

定义网络连接类型:

public static final int NETTYPE_NULL = 0x00; //未连接网络

public static final int NETTYPE_WIFI = 0x01; //WIFI

public static final int NETTYPE_MOBILE = 0x02;//MOBILE

判断网络连接类型:

/*

 * 获取当前网络类型

 * @param context

 * @return

 */

public int getNetType(Context context) {

    int netType = NETTYPE_NULL;

    ConnectivityManager connectivityManager = (ConnectivityManager)context

            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

    if (activeNetworkInfo == null) {

        return netType;

    }

    

    int nType = activeNetworkInfo.getType();

    if (nType == ConnectivityManager.TYPE_WIFI) {

        netType = NETTYPE_WIFI;

    }else if (netType == ConnectivityManager.TYPE_MOBILE) {

        netType = NETTYPE_MOBILE;

    }

    

    return netType;

}

当然,想访问网络状态,AndroidMainfest.xml中要加入权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 

你可能感兴趣的:(android)