Android 判断网络状态
jopen
9年前
Android手机同时支持WIFI和3G, 判断网络连接, 判断网络类型(WIFI或3G).
权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
判断网络连接
/** * 判断网络是否可用, 在使用网络请求是预先使用此方法进行检查, 以节省资源. * * @return 可用状态 */ public static boolean isNetAvailable() { Context context = App.getAppContext(); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); return (info != null && info.isAvailable() && info.isConnected()); }
判断网络类型
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // 3G State mobile = conMan.getNetworkInfo(0).getState(); // WIFI State wifi = conMan.getNetworkInfo(1).getState(); if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) { // TODO: in mobile do something } else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) { // TODO: in wifi do something }
更加精细的网络类型:
TelephonyManager#getNetworkType or NetworkInfo#getSubtypeName
来自:http://blog.csdn.net/caroline_wendy/article/details/48468495